blob: 1f70bf60867215c982a7954c24f68a789fba92be [file] [log] [blame]
Brian Silverman9809c5f2022-07-23 16:12:23 -07001#![warn(unsafe_op_in_unsafe_fn)]
2
3//! This module provides a Rust async runtime on top of the C++ `aos::EventLoop` interface.
4//!
5//! # Rust async with `aos::EventLoop`
6//!
7//! The async runtimes we create are not general-purpose. They may only await the objects provided
8//! by this module. Awaiting anything else will hang, until it is woken which will panic. Also,
9//! doing any long-running task (besides await) will block the C++ EventLoop thread, which is
10//! usually bad.
11//!
12//! ## Multiple tasks
13//!
14//! This runtime only supports a single task (aka a single [`Future`]) at a time. For many use
15//! cases, this is sufficient. If you want more than that, one of these may be appropriate:
16//!
17//! 1. If you have a small number of tasks determined at compile time, [`futures::join`] can await
18//! them all simultaneously.
19//! 2. [`futures::stream::FuturesUnordered`] can wait on a variable number of futures. It also
20//! supports adding them at runtime. Consider something like
21//! `FuturesUnordered<Pin<Box<dyn Future<Output = ()>>>` if you want a generic "container of any
22//! future".
23//! 3. Multiple applications are better suited to multiple `EventLoopRuntime`s, on separate
24//! `aos::EventLoop`s. Otherwise they can't send messages to each other, among other
25//! restrictions. https://github.com/frc971/971-Robot-Code/issues/12 covers creating an adapter
26//! that provides multiple `EventLoop`s on top of a single underlying implementation.
27//!
28//! ## Design
29//!
30//! The design of this is tricky. This is a complicated API interface between C++ and Rust. The big
31//! considerations in arriving at this design include:
32//! * `EventLoop` implementations alias the objects they're returning from C++, which means
33//! creating Rust unique references to them is unsound. See
34//! https://github.com/google/autocxx/issues/1146 for details.
35//! * For various reasons autocxx can't directly wrap APIs using types ergonomic for C++. This and
36//! the previous point mean we wrap all of the C++ objects specifically for this class.
Brian Silverman2ee175e2023-07-11 16:32:08 -070037//! * Rust's lifetimes are only flexible enough to track everything with a single big lifetime.
38//! All the callbacks can store references to things tied to the event loop's lifetime, but no
39//! other lifetimes.
Brian Silverman9809c5f2022-07-23 16:12:23 -070040//! * We can't use [`futures::stream::Stream`] and all of its nice [`futures::stream::StreamExt`]
41//! helpers for watchers because we need lifetime-generic `Item` types. Effectively we're making
42//! a lending stream. This is very close to lending iterators, which is one of the motivating
43//! examples for generic associated types (https://github.com/rust-lang/rust/issues/44265).
44
Brian Silverman1431a772022-08-31 20:44:36 -070045use std::{
46 fmt,
47 future::Future,
48 marker::PhantomData,
Brian Silverman2ee175e2023-07-11 16:32:08 -070049 mem::ManuallyDrop,
Adam Snaidercc8c2f72023-06-25 20:56:13 -070050 ops::Add,
Brian Silverman1431a772022-08-31 20:44:36 -070051 panic::{catch_unwind, AssertUnwindSafe},
52 pin::Pin,
53 slice,
54 task::Poll,
55 time::Duration,
56};
Brian Silverman9809c5f2022-07-23 16:12:23 -070057
58use autocxx::{
Austin Schuhdad7a812023-07-26 21:11:22 -070059 subclass::{subclass, CppSubclass},
Brian Silverman9809c5f2022-07-23 16:12:23 -070060 WithinBox,
61};
62use cxx::UniquePtr;
Brian Silverman90221f82022-08-22 23:46:09 -070063use flatbuffers::{root_unchecked, Follow, FollowWith, FullyQualifiedName};
Adam Snaider163800b2023-07-12 00:21:17 -040064use futures::{future::pending, future::FusedFuture, never::Never};
Brian Silverman9809c5f2022-07-23 16:12:23 -070065use thiserror::Error;
66use uuid::Uuid;
67
Brian Silverman90221f82022-08-22 23:46:09 -070068pub use aos_configuration::{Channel, Configuration, Node};
69use aos_configuration::{ChannelLookupError, ConfigurationExt};
70
Brian Silverman9809c5f2022-07-23 16:12:23 -070071pub use aos_uuid::UUID;
Brian Silverman2ee175e2023-07-11 16:32:08 -070072pub use ffi::aos::EventLoopRuntime as CppEventLoopRuntime;
Adam Snaider163800b2023-07-12 00:21:17 -040073pub use ffi::aos::ExitHandle as CppExitHandle;
Brian Silverman9809c5f2022-07-23 16:12:23 -070074
75autocxx::include_cpp! (
76#include "aos/events/event_loop_runtime.h"
77
78safety!(unsafe)
79
80generate_pod!("aos::Context")
81generate!("aos::WatcherForRust")
82generate!("aos::RawSender_Error")
83generate!("aos::SenderForRust")
84generate!("aos::FetcherForRust")
Brian Silverman76f48362022-08-24 21:09:08 -070085generate!("aos::OnRunForRust")
Brian Silverman9809c5f2022-07-23 16:12:23 -070086generate!("aos::EventLoopRuntime")
Adam Snaider163800b2023-07-12 00:21:17 -040087generate!("aos::ExitHandle")
Adam Snaidercc8c2f72023-06-25 20:56:13 -070088generate!("aos::TimerForRust")
Brian Silverman9809c5f2022-07-23 16:12:23 -070089
90subclass!("aos::ApplicationFuture", RustApplicationFuture)
91
92extern_cpp_type!("aos::Configuration", crate::Configuration)
93extern_cpp_type!("aos::Channel", crate::Channel)
94extern_cpp_type!("aos::Node", crate::Node)
95extern_cpp_type!("aos::UUID", crate::UUID)
96);
97
98pub type EventLoop = ffi::aos::EventLoop;
99
Brian Silverman2ee175e2023-07-11 16:32:08 -0700100/// A marker type which is invariant with respect to the given lifetime.
101///
102/// When interacting with functions that take and return things with a given lifetime, the lifetime
103/// becomes invariant. Because we don't store these functions as Rust types, we need a type like
104/// this to tell the Rust compiler that it can't substitute a shorter _or_ longer lifetime.
105pub type InvariantLifetime<'a> = PhantomData<fn(&'a ()) -> &'a ()>;
106
Brian Silverman9809c5f2022-07-23 16:12:23 -0700107/// # Safety
108///
109/// This should have a `'event_loop` lifetime and `future` should include that in its type, but
110/// autocxx's subclass doesn't support that. Even if it did, it wouldn't be enforced. C++ is
111/// enforcing the lifetime: it destroys this object along with the C++ `EventLoopRuntime`, which
112/// must be outlived by the EventLoop.
113#[doc(hidden)]
Austin Schuhdad7a812023-07-26 21:11:22 -0700114#[subclass]
Brian Silverman9809c5f2022-07-23 16:12:23 -0700115pub struct RustApplicationFuture {
116 /// This logically has a `'event_loop` bound, see the class comment for details.
117 future: Pin<Box<dyn Future<Output = Never>>>,
118}
119
120impl ffi::aos::ApplicationFuture_methods for RustApplicationFuture {
Brian Silverman1431a772022-08-31 20:44:36 -0700121 fn Poll(&mut self) -> bool {
122 catch_unwind(AssertUnwindSafe(|| {
123 // This is always allowed because it can never create a value of type `Ready<Never>` to
124 // return, so it must always return `Pending`. That also means the value it returns doesn't
125 // mean anything, so we ignore it.
126 let _ = Pin::new(&mut self.future)
127 .poll(&mut std::task::Context::from_waker(&panic_waker()));
128 }))
129 .is_ok()
Brian Silverman9809c5f2022-07-23 16:12:23 -0700130 }
131}
132
133impl RustApplicationFuture {
134 pub fn new<'event_loop>(
135 future: impl Future<Output = Never> + 'event_loop,
136 ) -> UniquePtr<ffi::aos::ApplicationFuture> {
137 /// # Safety
138 ///
139 /// This completely removes the `'event_loop` lifetime, the caller must ensure that is
140 /// sound.
141 unsafe fn remove_lifetime<'event_loop>(
142 future: Pin<Box<dyn Future<Output = Never> + 'event_loop>>,
143 ) -> Pin<Box<dyn Future<Output = Never>>> {
144 // SAFETY: Caller is responsible.
145 unsafe { std::mem::transmute(future) }
146 }
147
148 Self::as_ApplicationFuture_unique_ptr(Self::new_cpp_owned(Self {
149 // SAFETY: C++ manages observing the lifetime, see [`RustApplicationFuture`] for
150 // details.
151 future: unsafe { remove_lifetime(Box::pin(future)) },
152 cpp_peer: Default::default(),
153 }))
154 }
155}
156
Brian Silverman2ee175e2023-07-11 16:32:08 -0700157/// An abstraction for objects which hold an `aos::EventLoop` from Rust code.
158///
159/// If you have an `aos::EventLoop` provided from C++ code, don't use this, just call
160/// [`EventLoopRuntime.new`] directly.
161///
162/// # Safety
163///
164/// Objects implementing this trait *must* have mostly-exclusive (except for running it) ownership
165/// of the `aos::EventLoop` *for its entire lifetime*, which *must* be dropped when this object is.
166/// See [`EventLoopRuntime.new`]'s safety requirements for why this can be important and details of
167/// mostly-exclusive. In other words, nothing else may mutate it in any way except processing events
168/// (including dropping, because this object has to be the one to drop it).
169///
170/// This also implies semantics similar to `Pin<&mut ffi::aos::EventLoop>` for the underlying object.
171/// Implementations of this trait must have exclusive ownership of it, and the underlying object
172/// must not be moved.
173pub unsafe trait EventLoopHolder {
174 /// Converts this holder into a raw C++ pointer. This may be fed through other Rust and C++
175 /// code, and eventually passed back to [`from_raw`].
176 fn into_raw(self) -> *mut ffi::aos::EventLoop;
177
178 /// Converts a raw C++ pointer back to a holder object.
179 ///
180 /// # Safety
181 ///
182 /// `raw` must be the result of [`into_raw`] on an instance of this same type. These raw
183 /// pointers *are not* interchangeable between implementations of this trait.
184 unsafe fn from_raw(raw: *mut ffi::aos::EventLoop) -> Self;
185}
186
187/// Owns an [`EventLoopRuntime`] and its underlying `aos::EventLoop`, with safe management of the
188/// associated Rust lifetimes.
189pub struct EventLoopRuntimeHolder<T: EventLoopHolder>(
190 ManuallyDrop<Pin<Box<CppEventLoopRuntime>>>,
191 PhantomData<T>,
192);
193
194impl<T: EventLoopHolder> EventLoopRuntimeHolder<T> {
195 /// Creates a new [`EventLoopRuntime`] and runs an initialization function on it. This is a
196 /// safe wrapper around [`EventLoopRuntime.new`] (although see [`EventLoopHolder`]'s safety
197 /// requirements, part of them are just delegated there).
198 ///
199 /// If you have an `aos::EventLoop` provided from C++ code, don't use this, just call
200 /// [`EventLoopRuntime.new`] directly.
201 ///
202 /// All setup of the runtime must be performed with `fun`, which is called before this function
203 /// returns. `fun` may create further objects to use in async functions via [`EventLoop.spawn`]
204 /// etc, but it is the only place to set things up before the EventLoop is run.
205 ///
206 /// `fun` cannot capture things outside of the event loop, because the event loop might outlive
207 /// them:
208 /// ```compile_fail
209 /// # use aos_events_event_loop_runtime::*;
210 /// # fn bad(event_loop: impl EventLoopHolder) {
211 /// let mut x = 0;
212 /// EventLoopRuntimeHolder::new(event_loop, |runtime| {
213 /// runtime.spawn(async {
214 /// x = 1;
215 /// loop {}
216 /// });
217 /// });
218 /// # }
219 /// ```
220 ///
221 /// But it can capture `'event_loop` references:
222 /// ```
223 /// # use aos_events_event_loop_runtime::*;
224 /// # use aos_configuration::ChannelExt;
225 /// # fn good(event_loop: impl EventLoopHolder) {
226 /// EventLoopRuntimeHolder::new(event_loop, |runtime| {
227 /// let channel = runtime.get_raw_channel("/test", "aos.examples.Ping").unwrap();
228 /// runtime.spawn(async {
229 /// loop {
230 /// eprintln!("{:?}", channel.type_());
231 /// }
232 /// });
233 /// });
234 /// # }
235 /// ```
236 pub fn new<F>(event_loop: T, fun: F) -> Self
237 where
238 F: for<'event_loop> FnOnce(&mut EventLoopRuntime<'event_loop>),
239 {
240 // SAFETY: The EventLoopRuntime never escapes this function, which means the only code that
241 // observes its lifetime is `fun`. `fun` must be generic across any value of its
242 // `'event_loop` lifetime parameter, which means we can choose any lifetime here, which
243 // satisfies the safety requirements.
244 //
245 // This is a similar pattern as `std::thread::scope`, `ghost-cell`, etc. Note that unlike
246 // `std::thread::scope`, our inner functions (the async ones) are definitely not allowed to
247 // capture things from the calling scope of this function, so there's no `'env` equivalent.
248 // `ghost-cell` ends up looking very similar despite doing different things with the
249 // pattern, while `std::thread::scope` has a lot of additional complexity to achieve a
250 // similar result.
251 //
252 // `EventLoopHolder`s safety requirements prevent anybody else from touching the underlying
253 // `aos::EventLoop`.
254 let mut runtime = unsafe { EventLoopRuntime::new(event_loop.into_raw()) };
255 fun(&mut runtime);
256 Self(ManuallyDrop::new(runtime.into_cpp()), PhantomData)
257 }
258}
259
260impl<T: EventLoopHolder> Drop for EventLoopRuntimeHolder<T> {
261 fn drop(&mut self) {
Adam Snaider48a54682023-09-28 21:50:42 -0700262 let event_loop = self.0.event_loop();
Brian Silverman2ee175e2023-07-11 16:32:08 -0700263 // SAFETY: We're not going to touch this field again. The underlying EventLoop will not be
264 // run again because we're going to drop it next.
265 unsafe { ManuallyDrop::drop(&mut self.0) };
266 // SAFETY: We took this from `into_raw`, and we just dropped the runtime which may contain
267 // Rust references to it.
268 unsafe { drop(T::from_raw(event_loop)) };
269 }
270}
271
Brian Silverman9809c5f2022-07-23 16:12:23 -0700272pub struct EventLoopRuntime<'event_loop>(
273 Pin<Box<ffi::aos::EventLoopRuntime>>,
Brian Silverman2ee175e2023-07-11 16:32:08 -0700274 // See documentation of [`new`] for details.
275 InvariantLifetime<'event_loop>,
Brian Silverman9809c5f2022-07-23 16:12:23 -0700276);
277
278/// Manages the Rust interface to a *single* `aos::EventLoop`. This is intended to be used by a
279/// single application.
280impl<'event_loop> EventLoopRuntime<'event_loop> {
Brian Silverman2ee175e2023-07-11 16:32:08 -0700281 /// Creates a new runtime. This must be the only user of the underlying `aos::EventLoop`.
282 ///
283 /// Consider using [`EventLoopRuntimeHolder.new`] instead, if you're working with an
284 /// `aos::EventLoop` owned (indirectly) by Rust code.
285 ///
286 /// One common pattern is calling this in the constructor of an object whose lifetime is managed
287 /// by C++; C++ doesn't inherit the Rust lifetime but we do have a lot of C++ code that obeys
288 /// these rules implicitly.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700289 ///
290 /// Call [`spawn`] to respond to events. The non-event-driven APIs may be used without calling
291 /// this.
292 ///
293 /// This is an async runtime, but it's a somewhat unusual one. See the module-level
294 /// documentation for details.
295 ///
296 /// # Safety
297 ///
Brian Silverman2ee175e2023-07-11 16:32:08 -0700298 /// This function is where all the tricky lifetime guarantees to ensure soundness come
299 /// together. It all boils down to choosing `'event_loop` correctly, which is very complicated.
300 /// Here are the rules:
Brian Silverman9809c5f2022-07-23 16:12:23 -0700301 ///
Brian Silverman2ee175e2023-07-11 16:32:08 -0700302 /// 1. The `aos::EventLoop` APIs, and any other consumer-facing APIs, of the underlying
303 /// `aos::EventLoop` *must* be exclusively used by this object, and things it calls, for
304 /// `'event_loop`.
305 /// 2. `'event_loop` extends until after the last time the underlying `aos::EventLoop` is run.
306 /// This is often beyond the lifetime of this Rust `EventLoopRuntime` object.
307 /// 3. `'event_loop` must outlive this object, because this object stores references to the
308 /// underlying `aos::EventLoop`.
309 /// 4. Any other references stored in the underlying `aos::EventLoop` must be valid for
310 /// `'event_loop`. The easiest way to ensure this is by not using the `aos::EventLoop` before
311 /// passing it to this object.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700312 ///
Brian Silverman2ee175e2023-07-11 16:32:08 -0700313 /// Here are some corollaries:
314 ///
315 /// 1. The underlying `aos::EventLoop` must be dropped after this object.
316 /// 2. This object will store various references valid for `'event_loop` with a duration of
317 /// `'event_loop`, which is safe as long as they're both the same `'event_loop`. Note that
318 /// this requires this type to be invariant with respect to `'event_loop`.
319 /// 3. `event_loop` (the pointer being passed in) is effectively `Pin`, which is also implied
320 /// by the underlying `aos::EventLoop` C++ type.
321 /// 4. You cannot create multiple `EventLoopRuntime`s from the same underlying `aos::EventLoop`
322 /// or otherwise use it from a different application. The first one may create
323 /// mutable Rust references while the second one expects exclusive ownership, for example.
324 ///
325 /// `aos::EventLoop`'s public API is exclusively for consumers of the event loop. Some
326 /// subclasses extend this API. Additionally, all useful implementations of `aos::EventLoop`
327 /// must have some way to process events. Sometimes this is additional API surface (such as
328 /// `aos::ShmEventLoop`), in other cases comes via other objects holding references to the
329 /// `aos::EventLoop` (such as `aos::SimulatedEventLoopFactory`). This access to run the event
330 /// loop functions independently of the consuming functions in every way except lifetime of the
331 /// `aos::EventLoop`, and may be used independently of `'event_loop`.
332 ///
333 /// ## Discussion of the rules
334 ///
335 /// Rule 1 is similar to rule 3 (they're both similar to mutable borrowing), but rule 1 extends
336 /// for the entire lifetime of the object instead of being limited to the lifetime of an
337 /// individual borrow by an instance of this type. This is similar to the way [`Pin`]'s
338 /// estrictions extend for the entire lifetime of the object, until it is dropped.
339 ///
340 /// Rule 2 and corollaries 2 and 3 go together, and are essential for making [`spawn`]ed tasks
341 /// useful. The `aos::EventLoop` is full of indirect circular references, both within itself
342 /// and via all of the callbacks. This is sound if all of these references have the *exact
343 /// same* Rust lifetime, which is `'event_loop`.
344 ///
345 /// ## Alternatives and why they don't work
346 ///
347 /// Making the argument `Pin<&'event_loop mut EventLoop>` would express some (but not all) of
348 /// these restrictions within the Rust type system. However, having an actual Rust mutable
349 /// reference like that prevents anything else from creating one via other pointers to the
350 /// same object from C++, which is a common operation. See the module-level documentation for
351 /// details.
352 ///
353 /// [`spawn`]ed tasks need to hold `&'event_loop` references to things like channels. Using a
354 /// separate `'config` lifetime wouldn't change much; the tasks still need to do things which
355 /// require them to not outlive something they don't control. This is fundamental to
356 /// self-referential objects, which `aos::EventLoop` is based around, but Rust requires unsafe
357 /// code to manage manually.
358 ///
359 /// ## Final cautions
360 ///
361 /// Following these rules is very tricky. Be very cautious calling this function. It exposes an
362 /// unbound lifetime, which means you should wrap it directly in a function that attaches a
363 /// correct lifetime.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700364 pub unsafe fn new(event_loop: *mut ffi::aos::EventLoop) -> Self {
365 Self(
366 // SAFETY: We push all the validity requirements for this up to our caller.
367 unsafe { ffi::aos::EventLoopRuntime::new(event_loop) }.within_box(),
Brian Silverman2ee175e2023-07-11 16:32:08 -0700368 InvariantLifetime::default(),
Brian Silverman9809c5f2022-07-23 16:12:23 -0700369 )
370 }
371
Brian Silverman2ee175e2023-07-11 16:32:08 -0700372 /// Creates a Rust wrapper from the underlying C++ object, with an unbound lifetime.
373 ///
374 /// This may never be useful, but it's here for this big scary comment to explain why it's not
375 /// useful.
376 ///
377 /// # Safety
378 ///
379 /// See [`new`] for safety restrictions on `'event_loop` when calling this. In particular, see
380 /// the note about how tricky doing this correctly is, and remember that for this function the
381 /// event loop in question isn't even an argument to this function so it's even trickier. Also
382 /// note that you cannot call this on the result of [`into_cpp`] without violating those
383 /// restrictions.
384 pub unsafe fn from_cpp(cpp: Pin<Box<ffi::aos::EventLoopRuntime>>) -> Self {
385 Self(cpp, InvariantLifetime::default())
386 }
387
388 /// Extracts the underlying C++ object, without the corresponding Rust lifetime. This is useful
389 /// to stop the propagation of Rust lifetimes without destroying the underlying object which
390 /// contains all the state.
391 ///
392 /// Note that you *cannot* call [`from_cpp`] on the result of this, because that will violate
393 /// [`from_cpp`]'s safety requirements.
394 pub fn into_cpp(self) -> Pin<Box<ffi::aos::EventLoopRuntime>> {
395 self.0
396 }
397
Brian Silverman9809c5f2022-07-23 16:12:23 -0700398 /// Returns the pointer passed into the constructor.
399 ///
400 /// The returned value should only be used for destroying it (_after_ `self` is dropped) or
401 /// calling other C++ APIs.
Adam Snaider48a54682023-09-28 21:50:42 -0700402 pub fn raw_event_loop(&self) -> *mut ffi::aos::EventLoop {
403 self.0.event_loop()
Brian Silverman9809c5f2022-07-23 16:12:23 -0700404 }
405
Brian Silverman90221f82022-08-22 23:46:09 -0700406 /// Returns a reference to the name of this EventLoop.
407 ///
408 /// TODO(Brian): Come up with a nice way to expose this safely, without memory allocations, for
409 /// logging etc.
410 ///
411 /// # Safety
412 ///
413 /// The result must not be used after C++ could change it. Unfortunately C++ can change this
414 /// name from most places, so you should be really careful what you do with the result.
415 pub unsafe fn raw_name(&self) -> &str {
416 self.0.name()
417 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700418
419 pub fn get_raw_channel(
420 &self,
421 name: &str,
422 typename: &str,
Brian Silverman9809c5f2022-07-23 16:12:23 -0700423 ) -> Result<&'event_loop Channel, ChannelLookupError> {
Brian Silverman90221f82022-08-22 23:46:09 -0700424 self.configuration().get_channel(
425 name,
426 typename,
427 // SAFETY: We're not calling any EventLoop methods while C++ is using this for the
428 // channel lookup.
429 unsafe { self.raw_name() },
430 self.node(),
431 )
Brian Silverman9809c5f2022-07-23 16:12:23 -0700432 }
433
Brian Silverman90221f82022-08-22 23:46:09 -0700434 pub fn get_channel<T: FullyQualifiedName>(
435 &self,
436 name: &str,
437 ) -> Result<&'event_loop Channel, ChannelLookupError> {
438 self.get_raw_channel(name, T::get_fully_qualified_name())
439 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700440
441 /// Starts running the given `task`, which may not return (as specified by its type). If you
442 /// want your task to stop, return the result of awaiting [`futures::future::pending`], which
443 /// will never complete. `task` will not be polled after the underlying `aos::EventLoop` exits.
444 ///
Brian Silverman76f48362022-08-24 21:09:08 -0700445 /// Note that task will be polled immediately, to give it a chance to initialize. If you want to
446 /// defer work until the event loop starts running, await [`on_run`] in the task.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700447 ///
448 /// # Panics
449 ///
450 /// Panics if called more than once. See the module-level documentation for alternatives if you
451 /// want to do this.
452 ///
453 /// # Examples with interesting return types
454 ///
455 /// These are all valid futures which never return:
456 /// ```
457 /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) {
458 /// # use futures::{never::Never, future::pending};
459 /// async fn pending_wrapper() -> Never {
460 /// pending().await
461 /// }
462 /// async fn loop_forever() -> Never {
463 /// loop {}
464 /// }
465 ///
466 /// runtime.spawn(pending());
467 /// runtime.spawn(async { pending().await });
468 /// runtime.spawn(pending_wrapper());
469 /// runtime.spawn(async { loop {} });
470 /// runtime.spawn(loop_forever());
471 /// runtime.spawn(async { println!("all done"); pending().await });
472 /// # }
473 /// ```
474 /// but this is not:
475 /// ```compile_fail
476 /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) {
477 /// # use futures::ready;
478 /// runtime.spawn(ready());
479 /// # }
480 /// ```
481 /// and neither is this:
482 /// ```compile_fail
483 /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) {
484 /// # use futures::ready;
485 /// runtime.spawn(async { println!("all done") });
486 /// # }
487 /// ```
488 ///
489 /// # Examples with capturing
490 ///
491 /// The future can capture things. This is important to access other objects created from the
492 /// runtime, either before calling this function:
493 /// ```
494 /// # fn compile_check<'event_loop>(
495 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
496 /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel,
497 /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel,
498 /// # ) {
499 /// let mut watcher1 = runtime.make_raw_watcher(channel1);
500 /// let mut watcher2 = runtime.make_raw_watcher(channel2);
501 /// runtime.spawn(async move { loop {
502 /// watcher1.next().await;
503 /// watcher2.next().await;
504 /// }});
505 /// # }
506 /// ```
507 /// or after:
508 /// ```
509 /// # fn compile_check<'event_loop>(
510 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
511 /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel,
512 /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel,
513 /// # ) {
514 /// # use std::{cell::RefCell, rc::Rc};
515 /// let runtime = Rc::new(RefCell::new(runtime));
516 /// runtime.borrow_mut().spawn({
517 /// let mut runtime = runtime.clone();
518 /// async move {
519 /// let mut runtime = runtime.borrow_mut();
520 /// let mut watcher1 = runtime.make_raw_watcher(channel1);
521 /// let mut watcher2 = runtime.make_raw_watcher(channel2);
522 /// loop {
523 /// watcher1.next().await;
524 /// watcher2.next().await;
525 /// }
526 /// }
527 /// });
528 /// # }
529 /// ```
530 /// or both:
531 /// ```
532 /// # fn compile_check<'event_loop>(
533 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
534 /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel,
535 /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel,
536 /// # ) {
537 /// # use std::{cell::RefCell, rc::Rc};
538 /// let mut watcher1 = runtime.make_raw_watcher(channel1);
539 /// let runtime = Rc::new(RefCell::new(runtime));
540 /// runtime.borrow_mut().spawn({
541 /// let mut runtime = runtime.clone();
542 /// async move {
543 /// let mut runtime = runtime.borrow_mut();
544 /// let mut watcher2 = runtime.make_raw_watcher(channel2);
545 /// loop {
546 /// watcher1.next().await;
547 /// watcher2.next().await;
548 /// }
549 /// }
550 /// });
551 /// # }
552 /// ```
553 ///
554 /// But you cannot capture local variables:
555 /// ```compile_fail
556 /// # fn compile_check<'event_loop>(
557 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
558 /// # ) {
559 /// let mut local: i32 = 971;
560 /// let local = &mut local;
561 /// runtime.spawn(async move { loop {
562 /// println!("have: {}", local);
563 /// }});
564 /// # }
565 /// ```
Adam Snaider48a54682023-09-28 21:50:42 -0700566 pub fn spawn(&self, task: impl Future<Output = Never> + 'event_loop) {
567 self.0.Spawn(RustApplicationFuture::new(task));
Brian Silverman9809c5f2022-07-23 16:12:23 -0700568 }
569
570 pub fn configuration(&self) -> &'event_loop Configuration {
571 // SAFETY: It's always a pointer valid for longer than the underlying EventLoop.
572 unsafe { &*self.0.configuration() }
573 }
574
575 pub fn node(&self) -> Option<&'event_loop Node> {
576 // SAFETY: It's always a pointer valid for longer than the underlying EventLoop, or null.
577 unsafe { self.0.node().as_ref() }
578 }
579
580 pub fn monotonic_now(&self) -> MonotonicInstant {
581 MonotonicInstant(self.0.monotonic_now())
582 }
583
Ryan Yin683a8672022-11-09 20:44:20 -0800584 pub fn realtime_now(&self) -> RealtimeInstant {
585 RealtimeInstant(self.0.realtime_now())
586 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700587 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
588 /// part of `self.configuration()`, which will always have this lifetime.
589 ///
590 /// # Panics
591 ///
592 /// Dropping `self` before the returned object is dropped will panic.
Adam Snaider48a54682023-09-28 21:50:42 -0700593 pub fn make_raw_watcher(&self, channel: &'event_loop Channel) -> RawWatcher {
Brian Silverman9809c5f2022-07-23 16:12:23 -0700594 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
595 // the usual autocxx heuristics.
Adam Snaider48a54682023-09-28 21:50:42 -0700596 RawWatcher(unsafe { self.0.MakeWatcher(channel) }.within_box())
Brian Silverman9809c5f2022-07-23 16:12:23 -0700597 }
598
Brian Silverman90221f82022-08-22 23:46:09 -0700599 /// Provides type-safe async blocking access to messages on a channel. `T` should be a
600 /// generated flatbuffers table type, the lifetime parameter does not matter, using `'static`
601 /// is easiest.
602 ///
603 /// # Panics
604 ///
605 /// Dropping `self` before the returned object is dropped will panic.
Adam Snaider48a54682023-09-28 21:50:42 -0700606 pub fn make_watcher<T>(&self, channel_name: &str) -> Result<Watcher<T>, ChannelLookupError>
Brian Silverman90221f82022-08-22 23:46:09 -0700607 where
608 for<'a> T: FollowWith<'a>,
609 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
610 T: FullyQualifiedName,
611 {
612 let channel = self.get_channel::<T>(channel_name)?;
613 Ok(Watcher(self.make_raw_watcher(channel), PhantomData))
614 }
615
Brian Silverman9809c5f2022-07-23 16:12:23 -0700616 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
617 /// part of `self.configuration()`, which will always have this lifetime.
618 ///
619 /// # Panics
620 ///
621 /// Dropping `self` before the returned object is dropped will panic.
Adam Snaider48a54682023-09-28 21:50:42 -0700622 pub fn make_raw_sender(&self, channel: &'event_loop Channel) -> RawSender {
Brian Silverman9809c5f2022-07-23 16:12:23 -0700623 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
624 // the usual autocxx heuristics.
Adam Snaider48a54682023-09-28 21:50:42 -0700625 RawSender(unsafe { self.0.MakeSender(channel) }.within_box())
Brian Silverman9809c5f2022-07-23 16:12:23 -0700626 }
627
Brian Silverman90221f82022-08-22 23:46:09 -0700628 /// Allows sending messages on a channel with a type-safe API.
629 ///
630 /// # Panics
631 ///
632 /// Dropping `self` before the returned object is dropped will panic.
Adam Snaider48a54682023-09-28 21:50:42 -0700633 pub fn make_sender<T>(&self, channel_name: &str) -> Result<Sender<T>, ChannelLookupError>
Brian Silverman90221f82022-08-22 23:46:09 -0700634 where
635 for<'a> T: FollowWith<'a>,
636 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
637 T: FullyQualifiedName,
638 {
639 let channel = self.get_channel::<T>(channel_name)?;
640 Ok(Sender(self.make_raw_sender(channel), PhantomData))
641 }
642
Brian Silverman9809c5f2022-07-23 16:12:23 -0700643 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
644 /// part of `self.configuration()`, which will always have this lifetime.
645 ///
646 /// # Panics
647 ///
648 /// Dropping `self` before the returned object is dropped will panic.
Adam Snaider48a54682023-09-28 21:50:42 -0700649 pub fn make_raw_fetcher(&self, channel: &'event_loop Channel) -> RawFetcher {
Brian Silverman9809c5f2022-07-23 16:12:23 -0700650 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
651 // the usual autocxx heuristics.
Adam Snaider48a54682023-09-28 21:50:42 -0700652 RawFetcher(unsafe { self.0.MakeFetcher(channel) }.within_box())
Brian Silverman9809c5f2022-07-23 16:12:23 -0700653 }
654
Brian Silverman90221f82022-08-22 23:46:09 -0700655 /// Provides type-safe access to messages on a channel, without the ability to wait for a new
656 /// one. This provides APIs to get the latest message, and to follow along and retrieve each
657 /// message in order.
658 ///
659 /// # Panics
660 ///
661 /// Dropping `self` before the returned object is dropped will panic.
Adam Snaider48a54682023-09-28 21:50:42 -0700662 pub fn make_fetcher<T>(&self, channel_name: &str) -> Result<Fetcher<T>, ChannelLookupError>
Brian Silverman90221f82022-08-22 23:46:09 -0700663 where
664 for<'a> T: FollowWith<'a>,
665 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
666 T: FullyQualifiedName,
667 {
668 let channel = self.get_channel::<T>(channel_name)?;
669 Ok(Fetcher(self.make_raw_fetcher(channel), PhantomData))
670 }
671
Brian Silverman9809c5f2022-07-23 16:12:23 -0700672 // TODO(Brian): Expose timers and phased loops. Should we have `sleep`-style methods for those,
673 // instead of / in addition to mirroring C++ with separate setup and wait?
674
Brian Silverman76f48362022-08-24 21:09:08 -0700675 /// Returns a Future to wait until the underlying EventLoop is running. Once this resolves, all
676 /// subsequent code will have any realtime scheduling applied. This means it can rely on
677 /// consistent timing, but it can no longer create any EventLoop child objects or do anything
678 /// else non-realtime.
Adam Snaider48a54682023-09-28 21:50:42 -0700679 pub fn on_run(&self) -> OnRun {
680 OnRun(self.0.MakeOnRun().within_box())
Brian Silverman76f48362022-08-24 21:09:08 -0700681 }
682
683 pub fn is_running(&self) -> bool {
684 self.0.is_running()
685 }
Adam Snaidercc8c2f72023-06-25 20:56:13 -0700686
687 /// Returns an unarmed timer.
Adam Snaider48a54682023-09-28 21:50:42 -0700688 pub fn add_timer(&self) -> Timer {
689 Timer(self.0.AddTimer())
Adam Snaidercc8c2f72023-06-25 20:56:13 -0700690 }
691
692 /// Returns a timer that goes off every `duration`-long ticks.
Adam Snaider48a54682023-09-28 21:50:42 -0700693 pub fn add_interval(&self, duration: Duration) -> Timer {
Adam Snaidercc8c2f72023-06-25 20:56:13 -0700694 let mut timer = self.add_timer();
695 timer.setup(self.monotonic_now(), Some(duration));
696 timer
697 }
Adam Snaidercf0dac72023-10-02 14:41:58 -0700698
699 /// Sets the scheduler priority to run the event loop at.
700 pub fn set_realtime_priority(&self, priority: i32) {
701 self.0.SetRuntimeRealtimePriority(priority.into());
702 }
Adam Snaidercc8c2f72023-06-25 20:56:13 -0700703}
704
705/// An event loop primitive that allows sleeping asynchronously.
706///
707/// # Examples
708///
709/// ```no_run
710/// # use aos_events_event_loop_runtime::EventLoopRuntime;
711/// # use std::time::Duration;
712/// # fn compile_check(runtime: &mut EventLoopRuntime<'_>) {
713/// # let mut timer = runtime.add_timer();
714/// // Goes as soon as awaited.
715/// timer.setup(runtime.monotonic_now(), None);
716/// // Goes off once in 2 seconds.
717/// timer.setup(runtime.monotonic_now() + Duration::from_secs(2), None);
718/// // Goes off as soon as awaited and every 2 seconds afterwards.
719/// timer.setup(runtime.monotonic_now(), Some(Duration::from_secs(1)));
720/// async {
721/// for i in 0..10 {
722/// timer.tick().await;
723/// }
724/// // Timer won't off anymore. Next `tick` will never return.
725/// timer.disable();
726/// timer.tick().await;
727/// };
728/// # }
729/// ```
730pub struct Timer(UniquePtr<ffi::aos::TimerForRust>);
731
732/// A "tick" for a [`Timer`].
733///
734/// This is the raw future generated by the [`Timer::tick`] function.
735pub struct TimerTick<'a>(&'a mut Timer);
736
737impl Timer {
738 /// Arms the timer.
739 ///
740 /// The timer should sleep until `base`, `base + repeat`, `base + repeat * 2`, ...
741 /// If `repeat` is `None`, then the timer only expires once at `base`.
742 pub fn setup(&mut self, base: MonotonicInstant, repeat: Option<Duration>) {
743 self.0.pin_mut().Schedule(
744 base.0,
745 repeat
746 .unwrap_or(Duration::from_nanos(0))
747 .as_nanos()
748 .try_into()
749 .expect("Out of range: Internal clock uses 64 bits"),
750 );
751 }
752
753 /// Disarms the timer.
754 ///
755 /// Can be re-enabled by calling `setup` again.
756 pub fn disable(&mut self) {
757 self.0.pin_mut().Disable();
758 }
759
760 /// Returns `true` if the timer is enabled.
761 pub fn is_enabled(&self) -> bool {
762 !self.0.IsDisabled()
763 }
764
765 /// Sets the name of the timer.
766 ///
767 /// This can be useful to get a descriptive name in the timing reports.
768 pub fn set_name(&mut self, name: &str) {
769 self.0.pin_mut().set_name(name);
770 }
771
772 /// Gets the name of the timer.
773 pub fn name(&self) -> &str {
774 self.0.name()
775 }
776
777 /// Returns a tick which can be `.await`ed.
778 ///
779 /// This tick will resolve on the next timer expired.
780 pub fn tick(&mut self) -> TimerTick {
781 TimerTick(self)
782 }
783
784 /// Polls the timer, returning `[Poll::Ready]` only once the timer expired.
785 fn poll(&mut self) -> Poll<()> {
786 if self.0.pin_mut().Poll() {
787 Poll::Ready(())
788 } else {
789 Poll::Pending
790 }
791 }
792}
793
794impl Future for TimerTick<'_> {
795 type Output = ();
796
797 fn poll(mut self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<()> {
798 self.0.poll()
799 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700800}
801
Brian Silverman9809c5f2022-07-23 16:12:23 -0700802/// Provides async blocking access to messages on a channel. This will return every message on the
803/// channel, in order.
804///
805/// Use [`EventLoopRuntime::make_raw_watcher`] to create one of these.
806///
807/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
808/// for actually interpreting messages. You probably want a [`Watcher`] instead.
809///
810/// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical
811/// reasons.
812///
813/// # Design
814///
815/// We can't use [`futures::stream::Stream`] because our `Item` type is `Context<'_>`, which means
816/// it's different for each `self` lifetime so we can't write a single type alias for it. We could
817/// write an intermediate type with a generic lifetime that implements `Stream` and is returned
818/// from a `make_stream` method, but that's what `Stream` is doing in the first place so adding
819/// another level doesn't help anything.
820///
821/// We also drop the extraneous `cx` argument that isn't used by this implementation anyways.
822///
823/// We also run into some limitations in the borrow checker trying to implement `poll`, I think it's
824/// the same one mentioned here:
825/// https://blog.rust-lang.org/2022/08/05/nll-by-default.html#looking-forward-what-can-we-expect-for-the-borrow-checker-of-the-future
826/// We get around that one by moving the unbounded lifetime from the pointer dereference into the
827/// function with the if statement.
Brian Silverman90221f82022-08-22 23:46:09 -0700828// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
829#[repr(transparent)]
830pub struct RawWatcher(Pin<Box<ffi::aos::WatcherForRust>>);
831
Brian Silverman9809c5f2022-07-23 16:12:23 -0700832impl RawWatcher {
833 /// Returns a Future to await the next value. This can be canceled (ie dropped) at will,
834 /// without skipping any messages.
835 ///
836 /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You
837 /// will need to call this function again to get the succeeding message.
838 ///
839 /// # Examples
840 ///
841 /// The common use case is immediately awaiting the next message:
842 /// ```
843 /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
844 /// println!("received: {:?}", watcher.next().await);
845 /// # }
846 /// ```
847 ///
848 /// You can also await the first message from any of a set of channels:
849 /// ```
850 /// # async fn select(
851 /// # mut watcher1: aos_events_event_loop_runtime::RawWatcher,
852 /// # mut watcher2: aos_events_event_loop_runtime::RawWatcher,
853 /// # ) {
854 /// futures::select! {
855 /// message1 = watcher1.next() => println!("channel 1: {:?}", message1),
856 /// message2 = watcher2.next() => println!("channel 2: {:?}", message2),
857 /// }
858 /// # }
859 /// ```
860 ///
861 /// Note that due to the returned object borrowing the `self` reference, the borrow checker will
862 /// enforce only having a single of these returned objects at a time. Drop the previous message
863 /// before asking for the next one. That means this will not compile:
864 /// ```compile_fail
865 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
866 /// let first = watcher.next();
867 /// let second = watcher.next();
868 /// first.await;
869 /// # }
870 /// ```
871 /// and nor will this:
872 /// ```compile_fail
873 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
874 /// let first = watcher.next().await;
875 /// watcher.next();
876 /// println!("still have: {:?}", first);
877 /// # }
878 /// ```
879 /// but this is fine:
880 /// ```
881 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
882 /// let first = watcher.next().await;
883 /// println!("have: {:?}", first);
884 /// watcher.next();
885 /// # }
886 /// ```
887 pub fn next(&mut self) -> RawWatcherNext {
888 RawWatcherNext(Some(self))
889 }
890}
891
892/// The type returned from [`RawWatcher::next`], see there for details.
893pub struct RawWatcherNext<'a>(Option<&'a mut RawWatcher>);
894
895impl<'a> Future for RawWatcherNext<'a> {
896 type Output = Context<'a>;
897 fn poll(mut self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<Context<'a>> {
898 let inner = self
899 .0
900 .take()
901 .expect("May not call poll after it returns Ready");
902 let maybe_context = inner.0.as_mut().PollNext();
903 if maybe_context.is_null() {
904 // We're not returning a reference into it, so we can safely replace the reference to
905 // use again in the future.
906 self.0.replace(inner);
907 Poll::Pending
908 } else {
909 // SAFETY: We just checked if it's null. If not, it will be a valid pointer. It will
910 // remain a valid pointer for the borrow of the underlying `RawWatcher` (ie `'a`)
911 // because we're dropping `inner` (which is that reference), so it will need to be
912 // borrowed again which cannot happen before the end of `'a`.
913 Poll::Ready(Context(unsafe { &*maybe_context }))
914 }
915 }
916}
917
918impl FusedFuture for RawWatcherNext<'_> {
919 fn is_terminated(&self) -> bool {
920 self.0.is_none()
921 }
922}
923
Brian Silverman90221f82022-08-22 23:46:09 -0700924/// Provides async blocking access to messages on a channel. This will return every message on the
925/// channel, in order.
926///
927/// Use [`EventLoopRuntime::make_watcher`] to create one of these.
928///
929/// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical
930/// reasons. See [`RawWatcher`]'s documentation for details.
931pub struct Watcher<T>(RawWatcher, PhantomData<*mut T>)
932where
933 for<'a> T: FollowWith<'a>,
934 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
935
936impl<T> Watcher<T>
937where
938 for<'a> T: FollowWith<'a>,
939 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
940{
941 /// Returns a Future to await the next value. This can be canceled (ie dropped) at will,
942 /// without skipping any messages.
943 ///
944 /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You
945 /// will need to call this function again to get the succeeding message.
946 ///
947 /// # Examples
948 ///
949 /// The common use case is immediately awaiting the next message:
950 /// ```
951 /// # use pong_rust_fbs::aos::examples::Pong;
952 /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
953 /// println!("received: {:?}", watcher.next().await);
954 /// # }
955 /// ```
956 ///
957 /// You can also await the first message from any of a set of channels:
958 /// ```
959 /// # use pong_rust_fbs::aos::examples::Pong;
960 /// # async fn select(
961 /// # mut watcher1: aos_events_event_loop_runtime::Watcher<Pong<'static>>,
962 /// # mut watcher2: aos_events_event_loop_runtime::Watcher<Pong<'static>>,
963 /// # ) {
964 /// futures::select! {
965 /// message1 = watcher1.next() => println!("channel 1: {:?}", message1),
966 /// message2 = watcher2.next() => println!("channel 2: {:?}", message2),
967 /// }
968 /// # }
969 /// ```
970 ///
971 /// Note that due to the returned object borrowing the `self` reference, the borrow checker will
972 /// enforce only having a single of these returned objects at a time. Drop the previous message
973 /// before asking for the next one. That means this will not compile:
974 /// ```compile_fail
975 /// # use pong_rust_fbs::aos::examples::Pong;
976 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
977 /// let first = watcher.next();
978 /// let second = watcher.next();
979 /// first.await;
980 /// # }
981 /// ```
982 /// and nor will this:
983 /// ```compile_fail
984 /// # use pong_rust_fbs::aos::examples::Pong;
985 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
986 /// let first = watcher.next().await;
987 /// watcher.next();
988 /// println!("still have: {:?}", first);
989 /// # }
990 /// ```
991 /// but this is fine:
992 /// ```
993 /// # use pong_rust_fbs::aos::examples::Pong;
994 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
995 /// let first = watcher.next().await;
996 /// println!("have: {:?}", first);
997 /// watcher.next();
998 /// # }
999 /// ```
1000 pub fn next(&mut self) -> WatcherNext<'_, <T as FollowWith<'_>>::Inner> {
1001 WatcherNext(self.0.next(), PhantomData)
1002 }
1003}
1004
1005/// The type returned from [`Watcher::next`], see there for details.
1006pub struct WatcherNext<'watcher, T>(RawWatcherNext<'watcher>, PhantomData<*mut T>)
1007where
1008 T: Follow<'watcher> + 'watcher;
1009
1010impl<'watcher, T> Future for WatcherNext<'watcher, T>
1011where
1012 T: Follow<'watcher> + 'watcher,
1013{
1014 type Output = TypedContext<'watcher, T>;
1015
1016 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
1017 Pin::new(&mut self.get_mut().0).poll(cx).map(|context|
1018 // SAFETY: The Watcher this was created from verified that the channel is the
1019 // right type, and the C++ guarantees that the buffer's type matches.
1020 TypedContext(context, PhantomData))
1021 }
1022}
1023
1024impl<'watcher, T> FusedFuture for WatcherNext<'watcher, T>
1025where
1026 T: Follow<'watcher> + 'watcher,
1027{
1028 fn is_terminated(&self) -> bool {
1029 self.0.is_terminated()
1030 }
1031}
1032
1033/// A wrapper around [`Context`] which exposes the flatbuffer message with the appropriate type.
1034pub struct TypedContext<'a, T>(
1035 // SAFETY: This must have a message, and it must be a valid `T` flatbuffer.
1036 Context<'a>,
1037 PhantomData<*mut T>,
1038)
1039where
1040 T: Follow<'a> + 'a;
1041
Brian Silverman90221f82022-08-22 23:46:09 -07001042impl<'a, T> TypedContext<'a, T>
1043where
1044 T: Follow<'a> + 'a,
1045{
1046 pub fn message(&self) -> Option<T::Inner> {
1047 self.0.data().map(|data| {
1048 // SAFETY: C++ guarantees that this is a valid flatbuffer. We guarantee it's the right
1049 // type based on invariants for our type.
1050 unsafe { root_unchecked::<T>(data) }
1051 })
1052 }
1053
1054 pub fn monotonic_event_time(&self) -> MonotonicInstant {
1055 self.0.monotonic_event_time()
1056 }
1057 pub fn monotonic_remote_time(&self) -> MonotonicInstant {
1058 self.0.monotonic_remote_time()
1059 }
Ryan Yin683a8672022-11-09 20:44:20 -08001060 pub fn realtime_event_time(&self) -> RealtimeInstant {
1061 self.0.realtime_event_time()
1062 }
1063 pub fn realtime_remote_time(&self) -> RealtimeInstant {
1064 self.0.realtime_remote_time()
1065 }
Brian Silverman90221f82022-08-22 23:46:09 -07001066 pub fn queue_index(&self) -> u32 {
1067 self.0.queue_index()
1068 }
1069 pub fn remote_queue_index(&self) -> u32 {
1070 self.0.remote_queue_index()
1071 }
1072 pub fn buffer_index(&self) -> i32 {
1073 self.0.buffer_index()
1074 }
1075 pub fn source_boot_uuid(&self) -> &Uuid {
1076 self.0.source_boot_uuid()
1077 }
1078}
1079
1080impl<'a, T> fmt::Debug for TypedContext<'a, T>
1081where
1082 T: Follow<'a> + 'a,
1083 T::Inner: fmt::Debug,
1084{
1085 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Brian Silverman90221f82022-08-22 23:46:09 -07001086 f.debug_struct("TypedContext")
1087 .field("monotonic_event_time", &self.monotonic_event_time())
1088 .field("monotonic_remote_time", &self.monotonic_remote_time())
Ryan Yin683a8672022-11-09 20:44:20 -08001089 .field("realtime_event_time", &self.realtime_event_time())
1090 .field("realtime_remote_time", &self.realtime_remote_time())
Brian Silverman90221f82022-08-22 23:46:09 -07001091 .field("queue_index", &self.queue_index())
1092 .field("remote_queue_index", &self.remote_queue_index())
1093 .field("message", &self.message())
1094 .field("buffer_index", &self.buffer_index())
1095 .field("source_boot_uuid", &self.source_boot_uuid())
1096 .finish()
1097 }
1098}
Brian Silverman9809c5f2022-07-23 16:12:23 -07001099
1100/// Provides access to messages on a channel, without the ability to wait for a new one. This
Brian Silverman90221f82022-08-22 23:46:09 -07001101/// provides APIs to get the latest message, and to follow along and retrieve each message in order.
Brian Silverman9809c5f2022-07-23 16:12:23 -07001102///
1103/// Use [`EventLoopRuntime::make_raw_fetcher`] to create one of these.
1104///
1105/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
1106/// for actually interpreting messages. You probably want a [`Fetcher`] instead.
Brian Silverman90221f82022-08-22 23:46:09 -07001107// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
1108#[repr(transparent)]
1109pub struct RawFetcher(Pin<Box<ffi::aos::FetcherForRust>>);
1110
Brian Silverman9809c5f2022-07-23 16:12:23 -07001111impl RawFetcher {
1112 pub fn fetch_next(&mut self) -> bool {
1113 self.0.as_mut().FetchNext()
1114 }
1115
1116 pub fn fetch(&mut self) -> bool {
1117 self.0.as_mut().Fetch()
1118 }
1119
1120 pub fn context(&self) -> Context {
1121 Context(self.0.context())
1122 }
1123}
1124
Brian Silverman90221f82022-08-22 23:46:09 -07001125/// Provides access to messages on a channel, without the ability to wait for a new one. This
1126/// provides APIs to get the latest message, and to follow along and retrieve each message in order.
1127///
1128/// Use [`EventLoopRuntime::make_fetcher`] to create one of these.
1129pub struct Fetcher<T>(
1130 // SAFETY: This must produce messages of type `T`.
1131 RawFetcher,
1132 PhantomData<*mut T>,
1133)
1134where
1135 for<'a> T: FollowWith<'a>,
1136 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
1137
1138impl<T> Fetcher<T>
1139where
1140 for<'a> T: FollowWith<'a>,
1141 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
1142{
1143 pub fn fetch_next(&mut self) -> bool {
1144 self.0.fetch_next()
1145 }
1146 pub fn fetch(&mut self) -> bool {
1147 self.0.fetch()
1148 }
1149
1150 pub fn context(&self) -> TypedContext<'_, <T as FollowWith<'_>>::Inner> {
1151 // SAFETY: We verified that this is the correct type, and C++ guarantees that the buffer's
1152 // type matches.
1153 TypedContext(self.0.context(), PhantomData)
1154 }
1155}
Brian Silverman9809c5f2022-07-23 16:12:23 -07001156
1157/// Allows sending messages on a channel.
1158///
1159/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
1160/// for actually creating messages to send. You probably want a [`Sender`] instead.
1161///
1162/// Use [`EventLoopRuntime::make_raw_sender`] to create one of these.
Brian Silverman90221f82022-08-22 23:46:09 -07001163// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
1164#[repr(transparent)]
1165pub struct RawSender(Pin<Box<ffi::aos::SenderForRust>>);
1166
Brian Silverman9809c5f2022-07-23 16:12:23 -07001167impl RawSender {
1168 fn buffer(&mut self) -> &mut [u8] {
1169 // SAFETY: This is a valid slice, and `u8` doesn't have any alignment requirements.
1170 unsafe { slice::from_raw_parts_mut(self.0.as_mut().data(), self.0.as_mut().size()) }
1171 }
1172
1173 /// Returns an object which can be used to build a message.
1174 ///
1175 /// # Examples
1176 ///
1177 /// ```
1178 /// # use pong_rust_fbs::aos::examples::PongBuilder;
1179 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
1180 /// # unsafe {
1181 /// let mut builder = sender.make_builder();
1182 /// let pong = PongBuilder::new(builder.fbb()).finish();
1183 /// builder.send(pong);
1184 /// # }
1185 /// # }
1186 /// ```
1187 ///
1188 /// You can bail out of building a message and build another one:
1189 /// ```
1190 /// # use pong_rust_fbs::aos::examples::PongBuilder;
1191 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
1192 /// # unsafe {
1193 /// let mut builder1 = sender.make_builder();
1194 /// builder1.fbb();
1195 /// let mut builder2 = sender.make_builder();
1196 /// let pong = PongBuilder::new(builder2.fbb()).finish();
1197 /// builder2.send(pong);
1198 /// # }
1199 /// # }
1200 /// ```
1201 /// but you cannot build two messages at the same time with a single builder:
1202 /// ```compile_fail
1203 /// # use pong_rust_fbs::aos::examples::PongBuilder;
1204 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
1205 /// # unsafe {
1206 /// let mut builder1 = sender.make_builder();
1207 /// let mut builder2 = sender.make_builder();
1208 /// PongBuilder::new(builder2.fbb()).finish();
1209 /// PongBuilder::new(builder1.fbb()).finish();
1210 /// # }
1211 /// # }
1212 /// ```
1213 pub fn make_builder(&mut self) -> RawBuilder {
1214 // TODO(Brian): Actually use the provided buffer instead of just using its
1215 // size to allocate a separate one.
1216 //
1217 // See https://github.com/google/flatbuffers/issues/7385.
1218 let fbb = flatbuffers::FlatBufferBuilder::with_capacity(self.buffer().len());
1219 RawBuilder {
1220 raw_sender: self,
1221 fbb,
1222 }
1223 }
1224}
1225
Brian Silverman9809c5f2022-07-23 16:12:23 -07001226/// Used for building a message. See [`RawSender::make_builder`] for details.
1227pub struct RawBuilder<'sender> {
1228 raw_sender: &'sender mut RawSender,
1229 fbb: flatbuffers::FlatBufferBuilder<'sender>,
1230}
1231
1232impl<'sender> RawBuilder<'sender> {
1233 pub fn fbb(&mut self) -> &mut flatbuffers::FlatBufferBuilder<'sender> {
1234 &mut self.fbb
1235 }
1236
1237 /// # Safety
1238 ///
1239 /// `T` must match the type of the channel of the sender this builder was created from.
1240 pub unsafe fn send<T>(mut self, root: flatbuffers::WIPOffset<T>) -> Result<(), SendError> {
1241 self.fbb.finish_minimal(root);
1242 let data = self.fbb.finished_data();
1243
1244 use ffi::aos::RawSender_Error as FfiError;
1245 // SAFETY: This is a valid buffer we're passing.
1246 match unsafe {
1247 self.raw_sender
1248 .0
1249 .as_mut()
1250 .CopyAndSend(data.as_ptr(), data.len())
1251 } {
1252 FfiError::kOk => Ok(()),
1253 FfiError::kMessagesSentTooFast => Err(SendError::MessagesSentTooFast),
1254 FfiError::kInvalidRedzone => Err(SendError::InvalidRedzone),
1255 }
1256 }
1257}
1258
Brian Silverman90221f82022-08-22 23:46:09 -07001259/// Allows sending messages on a channel with a type-safe API.
1260///
1261/// Use [`EventLoopRuntime::make_raw_sender`] to create one of these.
1262pub struct Sender<T>(
1263 // SAFETY: This must accept messages of type `T`.
1264 RawSender,
1265 PhantomData<*mut T>,
1266)
1267where
1268 for<'a> T: FollowWith<'a>,
1269 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
1270
1271impl<T> Sender<T>
1272where
1273 for<'a> T: FollowWith<'a>,
1274 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
1275{
1276 /// Returns an object which can be used to build a message.
1277 ///
1278 /// # Examples
1279 ///
1280 /// ```
1281 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
1282 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
1283 /// let mut builder = sender.make_builder();
1284 /// let pong = PongBuilder::new(builder.fbb()).finish();
1285 /// builder.send(pong);
1286 /// # }
1287 /// ```
1288 ///
1289 /// You can bail out of building a message and build another one:
1290 /// ```
1291 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
1292 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
1293 /// let mut builder1 = sender.make_builder();
1294 /// builder1.fbb();
1295 /// let mut builder2 = sender.make_builder();
1296 /// let pong = PongBuilder::new(builder2.fbb()).finish();
1297 /// builder2.send(pong);
1298 /// # }
1299 /// ```
1300 /// but you cannot build two messages at the same time with a single builder:
1301 /// ```compile_fail
1302 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
1303 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
1304 /// let mut builder1 = sender.make_builder();
1305 /// let mut builder2 = sender.make_builder();
1306 /// PongBuilder::new(builder2.fbb()).finish();
1307 /// PongBuilder::new(builder1.fbb()).finish();
1308 /// # }
1309 /// ```
1310 pub fn make_builder(&mut self) -> Builder<T> {
1311 Builder(self.0.make_builder(), PhantomData)
1312 }
1313}
1314
1315/// Used for building a message. See [`Sender::make_builder`] for details.
1316pub struct Builder<'sender, T>(
1317 // SAFETY: This must accept messages of type `T`.
1318 RawBuilder<'sender>,
1319 PhantomData<*mut T>,
1320)
1321where
1322 for<'a> T: FollowWith<'a>,
1323 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
1324
1325impl<'sender, T> Builder<'sender, T>
1326where
1327 for<'a> T: FollowWith<'a>,
1328 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
1329{
1330 pub fn fbb(&mut self) -> &mut flatbuffers::FlatBufferBuilder<'sender> {
1331 self.0.fbb()
1332 }
1333
1334 pub fn send<'a>(
1335 self,
1336 root: flatbuffers::WIPOffset<<T as FollowWith<'a>>::Inner>,
1337 ) -> Result<(), SendError> {
1338 // SAFETY: We guarantee this is the right type based on invariants for our type.
1339 unsafe { self.0.send(root) }
1340 }
1341}
1342
1343#[derive(Clone, Copy, Eq, PartialEq, Debug, Error)]
1344pub enum SendError {
1345 #[error("messages have been sent too fast on this channel")]
1346 MessagesSentTooFast,
1347 #[error("invalid redzone data, shared memory corruption detected")]
1348 InvalidRedzone,
1349}
1350
Brian Silverman9809c5f2022-07-23 16:12:23 -07001351#[repr(transparent)]
1352#[derive(Clone, Copy)]
1353pub struct Context<'context>(&'context ffi::aos::Context);
1354
1355impl fmt::Debug for Context<'_> {
1356 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Brian Silverman9809c5f2022-07-23 16:12:23 -07001357 f.debug_struct("Context")
1358 .field("monotonic_event_time", &self.monotonic_event_time())
1359 .field("monotonic_remote_time", &self.monotonic_remote_time())
Ryan Yin683a8672022-11-09 20:44:20 -08001360 .field("realtime_event_time", &self.realtime_event_time())
1361 .field("realtime_remote_time", &self.realtime_remote_time())
Brian Silverman9809c5f2022-07-23 16:12:23 -07001362 .field("queue_index", &self.queue_index())
1363 .field("remote_queue_index", &self.remote_queue_index())
1364 .field("size", &self.data().map(|data| data.len()))
1365 .field("buffer_index", &self.buffer_index())
1366 .field("source_boot_uuid", &self.source_boot_uuid())
1367 .finish()
1368 }
1369}
1370
Brian Silverman9809c5f2022-07-23 16:12:23 -07001371impl<'context> Context<'context> {
1372 pub fn monotonic_event_time(self) -> MonotonicInstant {
1373 MonotonicInstant(self.0.monotonic_event_time)
1374 }
1375
1376 pub fn monotonic_remote_time(self) -> MonotonicInstant {
1377 MonotonicInstant(self.0.monotonic_remote_time)
1378 }
1379
Ryan Yin683a8672022-11-09 20:44:20 -08001380 pub fn realtime_event_time(self) -> RealtimeInstant {
1381 RealtimeInstant(self.0.realtime_event_time)
1382 }
1383
1384 pub fn realtime_remote_time(self) -> RealtimeInstant {
1385 RealtimeInstant(self.0.realtime_remote_time)
1386 }
1387
Brian Silverman9809c5f2022-07-23 16:12:23 -07001388 pub fn queue_index(self) -> u32 {
1389 self.0.queue_index
1390 }
1391 pub fn remote_queue_index(self) -> u32 {
1392 self.0.remote_queue_index
1393 }
1394
1395 pub fn data(self) -> Option<&'context [u8]> {
1396 if self.0.data.is_null() {
1397 None
1398 } else {
1399 // SAFETY:
1400 // * `u8` has no alignment requirements
1401 // * It must be a single initialized flatbuffers buffer
1402 // * The borrow in `self.0` guarantees it won't be modified for `'context`
1403 Some(unsafe { slice::from_raw_parts(self.0.data as *const u8, self.0.size) })
1404 }
1405 }
1406
1407 pub fn buffer_index(self) -> i32 {
1408 self.0.buffer_index
1409 }
1410
1411 pub fn source_boot_uuid(self) -> &'context Uuid {
1412 // SAFETY: `self` has a valid C++ object. C++ guarantees that the return value will be
1413 // valid until something changes the context, which is `'context`.
1414 Uuid::from_bytes_ref(&self.0.source_boot_uuid)
1415 }
1416}
1417
Brian Silverman76f48362022-08-24 21:09:08 -07001418/// The type returned from [`EventLoopRuntime::on_run`], see there for details.
1419// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
1420#[repr(transparent)]
1421pub struct OnRun(Pin<Box<ffi::aos::OnRunForRust>>);
1422
1423impl Future for OnRun {
1424 type Output = ();
1425
1426 fn poll(self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<()> {
1427 if self.0.is_running() {
1428 Poll::Ready(())
1429 } else {
1430 Poll::Pending
1431 }
1432 }
1433}
1434
Brian Silverman9809c5f2022-07-23 16:12:23 -07001435/// Represents a `aos::monotonic_clock::time_point` in a natural Rust way. This
1436/// is intended to have the same API as [`std::time::Instant`], any missing
1437/// functionality can be added if useful.
Brian Silverman9809c5f2022-07-23 16:12:23 -07001438#[repr(transparent)]
1439#[derive(Clone, Copy, Eq, PartialEq)]
1440pub struct MonotonicInstant(i64);
1441
1442impl MonotonicInstant {
1443 /// `aos::monotonic_clock::min_time`, commonly used as a sentinel value.
1444 pub const MIN_TIME: Self = Self(i64::MIN);
1445
1446 pub fn is_min_time(self) -> bool {
1447 self == Self::MIN_TIME
1448 }
1449
1450 pub fn duration_since_epoch(self) -> Option<Duration> {
1451 if self.is_min_time() {
1452 None
1453 } else {
1454 Some(Duration::from_nanos(self.0.try_into().expect(
1455 "monotonic_clock::time_point should always be after the epoch",
1456 )))
1457 }
1458 }
1459}
1460
Adam Snaidercc8c2f72023-06-25 20:56:13 -07001461impl Add<Duration> for MonotonicInstant {
1462 type Output = MonotonicInstant;
1463
1464 fn add(self, rhs: Duration) -> Self::Output {
1465 Self(self.0 + i64::try_from(rhs.as_nanos()).unwrap())
1466 }
1467}
1468
Adam Snaiderde51c672023-09-28 21:55:43 -07001469impl From<MonotonicInstant> for i64 {
1470 fn from(value: MonotonicInstant) -> Self {
1471 value.0
1472 }
1473}
1474
Brian Silverman9809c5f2022-07-23 16:12:23 -07001475impl fmt::Debug for MonotonicInstant {
1476 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1477 self.duration_since_epoch().fmt(f)
1478 }
1479}
1480
Ryan Yin683a8672022-11-09 20:44:20 -08001481#[repr(transparent)]
1482#[derive(Clone, Copy, Eq, PartialEq)]
1483pub struct RealtimeInstant(i64);
1484
1485impl RealtimeInstant {
1486 pub const MIN_TIME: Self = Self(i64::MIN);
1487
1488 pub fn is_min_time(self) -> bool {
1489 self == Self::MIN_TIME
1490 }
1491
1492 pub fn duration_since_epoch(self) -> Option<Duration> {
1493 if self.is_min_time() {
1494 None
1495 } else {
1496 Some(Duration::from_nanos(self.0.try_into().expect(
1497 "monotonic_clock::time_point should always be after the epoch",
1498 )))
1499 }
1500 }
1501}
1502
Adam Snaiderde51c672023-09-28 21:55:43 -07001503impl From<RealtimeInstant> for i64 {
1504 fn from(value: RealtimeInstant) -> Self {
1505 value.0
1506 }
1507}
1508
Ryan Yin683a8672022-11-09 20:44:20 -08001509impl fmt::Debug for RealtimeInstant {
1510 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1511 self.duration_since_epoch().fmt(f)
1512 }
1513}
1514
Brian Silverman9809c5f2022-07-23 16:12:23 -07001515mod panic_waker {
1516 use std::task::{RawWaker, RawWakerVTable, Waker};
1517
1518 unsafe fn clone_panic_waker(_data: *const ()) -> RawWaker {
1519 raw_panic_waker()
1520 }
1521
1522 unsafe fn noop(_data: *const ()) {}
1523
1524 unsafe fn wake_panic(_data: *const ()) {
1525 panic!("Nothing should wake EventLoopRuntime's waker");
1526 }
1527
1528 const PANIC_WAKER_VTABLE: RawWakerVTable =
1529 RawWakerVTable::new(clone_panic_waker, wake_panic, wake_panic, noop);
1530
1531 fn raw_panic_waker() -> RawWaker {
1532 RawWaker::new(std::ptr::null(), &PANIC_WAKER_VTABLE)
1533 }
1534
1535 pub fn panic_waker() -> Waker {
1536 // SAFETY: The implementations of the RawWakerVTable functions do what is required of them.
1537 unsafe { Waker::from_raw(raw_panic_waker()) }
1538 }
1539}
1540
1541use panic_waker::panic_waker;
Adam Snaider163800b2023-07-12 00:21:17 -04001542
1543pub struct ExitHandle(UniquePtr<CppExitHandle>);
1544
1545impl ExitHandle {
1546 /// Exits the EventLoops represented by this handle. You probably want to immediately return
1547 /// from the context this is called in. Awaiting [`exit`] instead of using this function is an
1548 /// easy way to do that.
1549 pub fn exit_sync(mut self) {
1550 self.0.as_mut().unwrap().Exit();
1551 }
1552
1553 /// Exits the EventLoops represented by this handle, and never returns. Immediately awaiting
1554 /// this from a [`EventLoopRuntime::spawn`]ed task is usually what you want, it will ensure
1555 /// that no more code from that task runs.
1556 pub async fn exit(self) -> Never {
1557 self.exit_sync();
1558 pending().await
1559 }
1560}
1561
1562impl From<UniquePtr<CppExitHandle>> for ExitHandle {
1563 fn from(inner: UniquePtr<ffi::aos::ExitHandle>) -> Self {
1564 Self(inner)
1565 }
1566}