Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1 | #![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. |
| 37 | //! * Keeping track of all the lifetimes and creating appropriate references for the callbacks is |
| 38 | //! really hard in Rust. Even doing it for the library implementation turned out to be hard |
| 39 | //! enough to look for alternatives. I think you'd have to make extensive use of pointers, but |
| 40 | //! Rust makes that hard, and it's easy to create references in ways that violate Rust's |
| 41 | //! aliasing rules. |
| 42 | //! * We can't use [`futures::stream::Stream`] and all of its nice [`futures::stream::StreamExt`] |
| 43 | //! helpers for watchers because we need lifetime-generic `Item` types. Effectively we're making |
| 44 | //! a lending stream. This is very close to lending iterators, which is one of the motivating |
| 45 | //! examples for generic associated types (https://github.com/rust-lang/rust/issues/44265). |
| 46 | |
Brian Silverman | 1431a77 | 2022-08-31 20:44:36 -0700 | [diff] [blame] | 47 | use std::{ |
| 48 | fmt, |
| 49 | future::Future, |
| 50 | marker::PhantomData, |
| 51 | panic::{catch_unwind, AssertUnwindSafe}, |
| 52 | pin::Pin, |
| 53 | slice, |
| 54 | task::Poll, |
| 55 | time::Duration, |
| 56 | }; |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 57 | |
| 58 | use autocxx::{ |
Austin Schuh | dad7a81 | 2023-07-26 21:11:22 -0700 | [diff] [blame^] | 59 | subclass::{subclass, CppSubclass}, |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 60 | WithinBox, |
| 61 | }; |
| 62 | use cxx::UniquePtr; |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 63 | use flatbuffers::{root_unchecked, Follow, FollowWith, FullyQualifiedName}; |
Adam Snaider | 163800b | 2023-07-12 00:21:17 -0400 | [diff] [blame] | 64 | use futures::{future::pending, future::FusedFuture, never::Never}; |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 65 | use thiserror::Error; |
| 66 | use uuid::Uuid; |
| 67 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 68 | pub use aos_configuration::{Channel, Configuration, Node}; |
| 69 | use aos_configuration::{ChannelLookupError, ConfigurationExt}; |
| 70 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 71 | pub use aos_uuid::UUID; |
Adam Snaider | 163800b | 2023-07-12 00:21:17 -0400 | [diff] [blame] | 72 | pub use ffi::aos::ExitHandle as CppExitHandle; |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 73 | |
| 74 | autocxx::include_cpp! ( |
| 75 | #include "aos/events/event_loop_runtime.h" |
| 76 | |
| 77 | safety!(unsafe) |
| 78 | |
| 79 | generate_pod!("aos::Context") |
| 80 | generate!("aos::WatcherForRust") |
| 81 | generate!("aos::RawSender_Error") |
| 82 | generate!("aos::SenderForRust") |
| 83 | generate!("aos::FetcherForRust") |
Brian Silverman | 76f4836 | 2022-08-24 21:09:08 -0700 | [diff] [blame] | 84 | generate!("aos::OnRunForRust") |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 85 | generate!("aos::EventLoopRuntime") |
Adam Snaider | 163800b | 2023-07-12 00:21:17 -0400 | [diff] [blame] | 86 | generate!("aos::ExitHandle") |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 87 | |
| 88 | subclass!("aos::ApplicationFuture", RustApplicationFuture) |
| 89 | |
| 90 | extern_cpp_type!("aos::Configuration", crate::Configuration) |
| 91 | extern_cpp_type!("aos::Channel", crate::Channel) |
| 92 | extern_cpp_type!("aos::Node", crate::Node) |
| 93 | extern_cpp_type!("aos::UUID", crate::UUID) |
| 94 | ); |
| 95 | |
| 96 | pub type EventLoop = ffi::aos::EventLoop; |
| 97 | |
| 98 | /// # Safety |
| 99 | /// |
| 100 | /// This should have a `'event_loop` lifetime and `future` should include that in its type, but |
| 101 | /// autocxx's subclass doesn't support that. Even if it did, it wouldn't be enforced. C++ is |
| 102 | /// enforcing the lifetime: it destroys this object along with the C++ `EventLoopRuntime`, which |
| 103 | /// must be outlived by the EventLoop. |
| 104 | #[doc(hidden)] |
Austin Schuh | dad7a81 | 2023-07-26 21:11:22 -0700 | [diff] [blame^] | 105 | #[subclass] |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 106 | pub struct RustApplicationFuture { |
| 107 | /// This logically has a `'event_loop` bound, see the class comment for details. |
| 108 | future: Pin<Box<dyn Future<Output = Never>>>, |
| 109 | } |
| 110 | |
| 111 | impl ffi::aos::ApplicationFuture_methods for RustApplicationFuture { |
Brian Silverman | 1431a77 | 2022-08-31 20:44:36 -0700 | [diff] [blame] | 112 | fn Poll(&mut self) -> bool { |
| 113 | catch_unwind(AssertUnwindSafe(|| { |
| 114 | // This is always allowed because it can never create a value of type `Ready<Never>` to |
| 115 | // return, so it must always return `Pending`. That also means the value it returns doesn't |
| 116 | // mean anything, so we ignore it. |
| 117 | let _ = Pin::new(&mut self.future) |
| 118 | .poll(&mut std::task::Context::from_waker(&panic_waker())); |
| 119 | })) |
| 120 | .is_ok() |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 121 | } |
| 122 | } |
| 123 | |
| 124 | impl RustApplicationFuture { |
| 125 | pub fn new<'event_loop>( |
| 126 | future: impl Future<Output = Never> + 'event_loop, |
| 127 | ) -> UniquePtr<ffi::aos::ApplicationFuture> { |
| 128 | /// # Safety |
| 129 | /// |
| 130 | /// This completely removes the `'event_loop` lifetime, the caller must ensure that is |
| 131 | /// sound. |
| 132 | unsafe fn remove_lifetime<'event_loop>( |
| 133 | future: Pin<Box<dyn Future<Output = Never> + 'event_loop>>, |
| 134 | ) -> Pin<Box<dyn Future<Output = Never>>> { |
| 135 | // SAFETY: Caller is responsible. |
| 136 | unsafe { std::mem::transmute(future) } |
| 137 | } |
| 138 | |
| 139 | Self::as_ApplicationFuture_unique_ptr(Self::new_cpp_owned(Self { |
| 140 | // SAFETY: C++ manages observing the lifetime, see [`RustApplicationFuture`] for |
| 141 | // details. |
| 142 | future: unsafe { remove_lifetime(Box::pin(future)) }, |
| 143 | cpp_peer: Default::default(), |
| 144 | })) |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | pub struct EventLoopRuntime<'event_loop>( |
| 149 | Pin<Box<ffi::aos::EventLoopRuntime>>, |
| 150 | // This is the lifetime of the underlying EventLoop, which is held in C++ via `.0`. |
| 151 | PhantomData<&'event_loop mut ()>, |
| 152 | ); |
| 153 | |
| 154 | /// Manages the Rust interface to a *single* `aos::EventLoop`. This is intended to be used by a |
| 155 | /// single application. |
| 156 | impl<'event_loop> EventLoopRuntime<'event_loop> { |
| 157 | /// Creates a new runtime. This must be the only user of the underlying `aos::EventLoop`, or |
| 158 | /// things may panic unexpectedly. |
| 159 | /// |
| 160 | /// Call [`spawn`] to respond to events. The non-event-driven APIs may be used without calling |
| 161 | /// this. |
| 162 | /// |
| 163 | /// This is an async runtime, but it's a somewhat unusual one. See the module-level |
| 164 | /// documentation for details. |
| 165 | /// |
| 166 | /// # Safety |
| 167 | /// |
| 168 | /// `event_loop` must be valid for `'event_loop`. Effectively we want the argument to be |
| 169 | /// `&'event_loop mut EventLoop`, but we can't do that (see the module-level documentation for |
| 170 | /// details). |
| 171 | /// |
| 172 | /// This is a tricky thing to guarantee, be very cautious calling this function. It's an unbound |
| 173 | /// lifetime so you should probably wrap it in a function that directly attaches a known |
| 174 | /// lifetime. One common pattern is calling this in the constructor of an object whose lifetime |
| 175 | /// is managed by C++; C++ doesn't inherit the Rust lifetime but we do have a lot of C++ code |
| 176 | /// that obeys the rule of destroying the object before the EventLoop, which is equivalent to |
| 177 | /// this restriction. |
| 178 | /// |
| 179 | /// In Rust terms, this is equivalent to storing `event_loop` in the returned object, which |
| 180 | /// will dereference it throughout its lifetime, and the caller must guarantee this is sound. |
| 181 | pub unsafe fn new(event_loop: *mut ffi::aos::EventLoop) -> Self { |
| 182 | Self( |
| 183 | // SAFETY: We push all the validity requirements for this up to our caller. |
| 184 | unsafe { ffi::aos::EventLoopRuntime::new(event_loop) }.within_box(), |
| 185 | PhantomData, |
| 186 | ) |
| 187 | } |
| 188 | |
| 189 | /// Returns the pointer passed into the constructor. |
| 190 | /// |
| 191 | /// The returned value should only be used for destroying it (_after_ `self` is dropped) or |
| 192 | /// calling other C++ APIs. |
| 193 | pub fn raw_event_loop(&mut self) -> *mut ffi::aos::EventLoop { |
| 194 | self.0.as_mut().event_loop() |
| 195 | } |
| 196 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 197 | /// Returns a reference to the name of this EventLoop. |
| 198 | /// |
| 199 | /// TODO(Brian): Come up with a nice way to expose this safely, without memory allocations, for |
| 200 | /// logging etc. |
| 201 | /// |
| 202 | /// # Safety |
| 203 | /// |
| 204 | /// The result must not be used after C++ could change it. Unfortunately C++ can change this |
| 205 | /// name from most places, so you should be really careful what you do with the result. |
| 206 | pub unsafe fn raw_name(&self) -> &str { |
| 207 | self.0.name() |
| 208 | } |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 209 | |
| 210 | pub fn get_raw_channel( |
| 211 | &self, |
| 212 | name: &str, |
| 213 | typename: &str, |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 214 | ) -> Result<&'event_loop Channel, ChannelLookupError> { |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 215 | self.configuration().get_channel( |
| 216 | name, |
| 217 | typename, |
| 218 | // SAFETY: We're not calling any EventLoop methods while C++ is using this for the |
| 219 | // channel lookup. |
| 220 | unsafe { self.raw_name() }, |
| 221 | self.node(), |
| 222 | ) |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 223 | } |
| 224 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 225 | pub fn get_channel<T: FullyQualifiedName>( |
| 226 | &self, |
| 227 | name: &str, |
| 228 | ) -> Result<&'event_loop Channel, ChannelLookupError> { |
| 229 | self.get_raw_channel(name, T::get_fully_qualified_name()) |
| 230 | } |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 231 | |
| 232 | /// Starts running the given `task`, which may not return (as specified by its type). If you |
| 233 | /// want your task to stop, return the result of awaiting [`futures::future::pending`], which |
| 234 | /// will never complete. `task` will not be polled after the underlying `aos::EventLoop` exits. |
| 235 | /// |
Brian Silverman | 76f4836 | 2022-08-24 21:09:08 -0700 | [diff] [blame] | 236 | /// Note that task will be polled immediately, to give it a chance to initialize. If you want to |
| 237 | /// defer work until the event loop starts running, await [`on_run`] in the task. |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 238 | /// |
| 239 | /// # Panics |
| 240 | /// |
| 241 | /// Panics if called more than once. See the module-level documentation for alternatives if you |
| 242 | /// want to do this. |
| 243 | /// |
| 244 | /// # Examples with interesting return types |
| 245 | /// |
| 246 | /// These are all valid futures which never return: |
| 247 | /// ``` |
| 248 | /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) { |
| 249 | /// # use futures::{never::Never, future::pending}; |
| 250 | /// async fn pending_wrapper() -> Never { |
| 251 | /// pending().await |
| 252 | /// } |
| 253 | /// async fn loop_forever() -> Never { |
| 254 | /// loop {} |
| 255 | /// } |
| 256 | /// |
| 257 | /// runtime.spawn(pending()); |
| 258 | /// runtime.spawn(async { pending().await }); |
| 259 | /// runtime.spawn(pending_wrapper()); |
| 260 | /// runtime.spawn(async { loop {} }); |
| 261 | /// runtime.spawn(loop_forever()); |
| 262 | /// runtime.spawn(async { println!("all done"); pending().await }); |
| 263 | /// # } |
| 264 | /// ``` |
| 265 | /// but this is not: |
| 266 | /// ```compile_fail |
| 267 | /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) { |
| 268 | /// # use futures::ready; |
| 269 | /// runtime.spawn(ready()); |
| 270 | /// # } |
| 271 | /// ``` |
| 272 | /// and neither is this: |
| 273 | /// ```compile_fail |
| 274 | /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) { |
| 275 | /// # use futures::ready; |
| 276 | /// runtime.spawn(async { println!("all done") }); |
| 277 | /// # } |
| 278 | /// ``` |
| 279 | /// |
| 280 | /// # Examples with capturing |
| 281 | /// |
| 282 | /// The future can capture things. This is important to access other objects created from the |
| 283 | /// runtime, either before calling this function: |
| 284 | /// ``` |
| 285 | /// # fn compile_check<'event_loop>( |
| 286 | /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>, |
| 287 | /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel, |
| 288 | /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel, |
| 289 | /// # ) { |
| 290 | /// let mut watcher1 = runtime.make_raw_watcher(channel1); |
| 291 | /// let mut watcher2 = runtime.make_raw_watcher(channel2); |
| 292 | /// runtime.spawn(async move { loop { |
| 293 | /// watcher1.next().await; |
| 294 | /// watcher2.next().await; |
| 295 | /// }}); |
| 296 | /// # } |
| 297 | /// ``` |
| 298 | /// or after: |
| 299 | /// ``` |
| 300 | /// # fn compile_check<'event_loop>( |
| 301 | /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>, |
| 302 | /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel, |
| 303 | /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel, |
| 304 | /// # ) { |
| 305 | /// # use std::{cell::RefCell, rc::Rc}; |
| 306 | /// let runtime = Rc::new(RefCell::new(runtime)); |
| 307 | /// runtime.borrow_mut().spawn({ |
| 308 | /// let mut runtime = runtime.clone(); |
| 309 | /// async move { |
| 310 | /// let mut runtime = runtime.borrow_mut(); |
| 311 | /// let mut watcher1 = runtime.make_raw_watcher(channel1); |
| 312 | /// let mut watcher2 = runtime.make_raw_watcher(channel2); |
| 313 | /// loop { |
| 314 | /// watcher1.next().await; |
| 315 | /// watcher2.next().await; |
| 316 | /// } |
| 317 | /// } |
| 318 | /// }); |
| 319 | /// # } |
| 320 | /// ``` |
| 321 | /// or both: |
| 322 | /// ``` |
| 323 | /// # fn compile_check<'event_loop>( |
| 324 | /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>, |
| 325 | /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel, |
| 326 | /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel, |
| 327 | /// # ) { |
| 328 | /// # use std::{cell::RefCell, rc::Rc}; |
| 329 | /// let mut watcher1 = runtime.make_raw_watcher(channel1); |
| 330 | /// let runtime = Rc::new(RefCell::new(runtime)); |
| 331 | /// runtime.borrow_mut().spawn({ |
| 332 | /// let mut runtime = runtime.clone(); |
| 333 | /// async move { |
| 334 | /// let mut runtime = runtime.borrow_mut(); |
| 335 | /// let mut watcher2 = runtime.make_raw_watcher(channel2); |
| 336 | /// loop { |
| 337 | /// watcher1.next().await; |
| 338 | /// watcher2.next().await; |
| 339 | /// } |
| 340 | /// } |
| 341 | /// }); |
| 342 | /// # } |
| 343 | /// ``` |
| 344 | /// |
| 345 | /// But you cannot capture local variables: |
| 346 | /// ```compile_fail |
| 347 | /// # fn compile_check<'event_loop>( |
| 348 | /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>, |
| 349 | /// # ) { |
| 350 | /// let mut local: i32 = 971; |
| 351 | /// let local = &mut local; |
| 352 | /// runtime.spawn(async move { loop { |
| 353 | /// println!("have: {}", local); |
| 354 | /// }}); |
| 355 | /// # } |
| 356 | /// ``` |
| 357 | pub fn spawn(&mut self, task: impl Future<Output = Never> + 'event_loop) { |
Brian Silverman | 1431a77 | 2022-08-31 20:44:36 -0700 | [diff] [blame] | 358 | self.0.as_mut().Spawn(RustApplicationFuture::new(task)); |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 359 | } |
| 360 | |
| 361 | pub fn configuration(&self) -> &'event_loop Configuration { |
| 362 | // SAFETY: It's always a pointer valid for longer than the underlying EventLoop. |
| 363 | unsafe { &*self.0.configuration() } |
| 364 | } |
| 365 | |
| 366 | pub fn node(&self) -> Option<&'event_loop Node> { |
| 367 | // SAFETY: It's always a pointer valid for longer than the underlying EventLoop, or null. |
| 368 | unsafe { self.0.node().as_ref() } |
| 369 | } |
| 370 | |
| 371 | pub fn monotonic_now(&self) -> MonotonicInstant { |
| 372 | MonotonicInstant(self.0.monotonic_now()) |
| 373 | } |
| 374 | |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 375 | pub fn realtime_now(&self) -> RealtimeInstant { |
| 376 | RealtimeInstant(self.0.realtime_now()) |
| 377 | } |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 378 | /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is |
| 379 | /// part of `self.configuration()`, which will always have this lifetime. |
| 380 | /// |
| 381 | /// # Panics |
| 382 | /// |
| 383 | /// Dropping `self` before the returned object is dropped will panic. |
| 384 | pub fn make_raw_watcher(&mut self, channel: &'event_loop Channel) -> RawWatcher { |
| 385 | // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under |
| 386 | // the usual autocxx heuristics. |
| 387 | RawWatcher(unsafe { self.0.as_mut().MakeWatcher(channel) }.within_box()) |
| 388 | } |
| 389 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 390 | /// Provides type-safe async blocking access to messages on a channel. `T` should be a |
| 391 | /// generated flatbuffers table type, the lifetime parameter does not matter, using `'static` |
| 392 | /// is easiest. |
| 393 | /// |
| 394 | /// # Panics |
| 395 | /// |
| 396 | /// Dropping `self` before the returned object is dropped will panic. |
| 397 | pub fn make_watcher<T>(&mut self, channel_name: &str) -> Result<Watcher<T>, ChannelLookupError> |
| 398 | where |
| 399 | for<'a> T: FollowWith<'a>, |
| 400 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 401 | T: FullyQualifiedName, |
| 402 | { |
| 403 | let channel = self.get_channel::<T>(channel_name)?; |
| 404 | Ok(Watcher(self.make_raw_watcher(channel), PhantomData)) |
| 405 | } |
| 406 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 407 | /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is |
| 408 | /// part of `self.configuration()`, which will always have this lifetime. |
| 409 | /// |
| 410 | /// # Panics |
| 411 | /// |
| 412 | /// Dropping `self` before the returned object is dropped will panic. |
| 413 | pub fn make_raw_sender(&mut self, channel: &'event_loop Channel) -> RawSender { |
| 414 | // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under |
| 415 | // the usual autocxx heuristics. |
| 416 | RawSender(unsafe { self.0.as_mut().MakeSender(channel) }.within_box()) |
| 417 | } |
| 418 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 419 | /// Allows sending messages on a channel with a type-safe API. |
| 420 | /// |
| 421 | /// # Panics |
| 422 | /// |
| 423 | /// Dropping `self` before the returned object is dropped will panic. |
| 424 | pub fn make_sender<T>(&mut self, channel_name: &str) -> Result<Sender<T>, ChannelLookupError> |
| 425 | where |
| 426 | for<'a> T: FollowWith<'a>, |
| 427 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 428 | T: FullyQualifiedName, |
| 429 | { |
| 430 | let channel = self.get_channel::<T>(channel_name)?; |
| 431 | Ok(Sender(self.make_raw_sender(channel), PhantomData)) |
| 432 | } |
| 433 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 434 | /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is |
| 435 | /// part of `self.configuration()`, which will always have this lifetime. |
| 436 | /// |
| 437 | /// # Panics |
| 438 | /// |
| 439 | /// Dropping `self` before the returned object is dropped will panic. |
| 440 | pub fn make_raw_fetcher(&mut self, channel: &'event_loop Channel) -> RawFetcher { |
| 441 | // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under |
| 442 | // the usual autocxx heuristics. |
| 443 | RawFetcher(unsafe { self.0.as_mut().MakeFetcher(channel) }.within_box()) |
| 444 | } |
| 445 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 446 | /// Provides type-safe access to messages on a channel, without the ability to wait for a new |
| 447 | /// one. This provides APIs to get the latest message, and to follow along and retrieve each |
| 448 | /// message in order. |
| 449 | /// |
| 450 | /// # Panics |
| 451 | /// |
| 452 | /// Dropping `self` before the returned object is dropped will panic. |
| 453 | pub fn make_fetcher<T>(&mut self, channel_name: &str) -> Result<Fetcher<T>, ChannelLookupError> |
| 454 | where |
| 455 | for<'a> T: FollowWith<'a>, |
| 456 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 457 | T: FullyQualifiedName, |
| 458 | { |
| 459 | let channel = self.get_channel::<T>(channel_name)?; |
| 460 | Ok(Fetcher(self.make_raw_fetcher(channel), PhantomData)) |
| 461 | } |
| 462 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 463 | // TODO(Brian): Expose timers and phased loops. Should we have `sleep`-style methods for those, |
| 464 | // instead of / in addition to mirroring C++ with separate setup and wait? |
| 465 | |
Brian Silverman | 76f4836 | 2022-08-24 21:09:08 -0700 | [diff] [blame] | 466 | /// Returns a Future to wait until the underlying EventLoop is running. Once this resolves, all |
| 467 | /// subsequent code will have any realtime scheduling applied. This means it can rely on |
| 468 | /// consistent timing, but it can no longer create any EventLoop child objects or do anything |
| 469 | /// else non-realtime. |
| 470 | pub fn on_run(&mut self) -> OnRun { |
| 471 | OnRun(self.0.as_mut().MakeOnRun().within_box()) |
| 472 | } |
| 473 | |
| 474 | pub fn is_running(&self) -> bool { |
| 475 | self.0.is_running() |
| 476 | } |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 477 | } |
| 478 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 479 | /// Provides async blocking access to messages on a channel. This will return every message on the |
| 480 | /// channel, in order. |
| 481 | /// |
| 482 | /// Use [`EventLoopRuntime::make_raw_watcher`] to create one of these. |
| 483 | /// |
| 484 | /// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs |
| 485 | /// for actually interpreting messages. You probably want a [`Watcher`] instead. |
| 486 | /// |
| 487 | /// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical |
| 488 | /// reasons. |
| 489 | /// |
| 490 | /// # Design |
| 491 | /// |
| 492 | /// We can't use [`futures::stream::Stream`] because our `Item` type is `Context<'_>`, which means |
| 493 | /// it's different for each `self` lifetime so we can't write a single type alias for it. We could |
| 494 | /// write an intermediate type with a generic lifetime that implements `Stream` and is returned |
| 495 | /// from a `make_stream` method, but that's what `Stream` is doing in the first place so adding |
| 496 | /// another level doesn't help anything. |
| 497 | /// |
| 498 | /// We also drop the extraneous `cx` argument that isn't used by this implementation anyways. |
| 499 | /// |
| 500 | /// We also run into some limitations in the borrow checker trying to implement `poll`, I think it's |
| 501 | /// the same one mentioned here: |
| 502 | /// 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 |
| 503 | /// We get around that one by moving the unbounded lifetime from the pointer dereference into the |
| 504 | /// function with the if statement. |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 505 | // SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL). |
| 506 | #[repr(transparent)] |
| 507 | pub struct RawWatcher(Pin<Box<ffi::aos::WatcherForRust>>); |
| 508 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 509 | impl RawWatcher { |
| 510 | /// Returns a Future to await the next value. This can be canceled (ie dropped) at will, |
| 511 | /// without skipping any messages. |
| 512 | /// |
| 513 | /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You |
| 514 | /// will need to call this function again to get the succeeding message. |
| 515 | /// |
| 516 | /// # Examples |
| 517 | /// |
| 518 | /// The common use case is immediately awaiting the next message: |
| 519 | /// ``` |
| 520 | /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::RawWatcher) { |
| 521 | /// println!("received: {:?}", watcher.next().await); |
| 522 | /// # } |
| 523 | /// ``` |
| 524 | /// |
| 525 | /// You can also await the first message from any of a set of channels: |
| 526 | /// ``` |
| 527 | /// # async fn select( |
| 528 | /// # mut watcher1: aos_events_event_loop_runtime::RawWatcher, |
| 529 | /// # mut watcher2: aos_events_event_loop_runtime::RawWatcher, |
| 530 | /// # ) { |
| 531 | /// futures::select! { |
| 532 | /// message1 = watcher1.next() => println!("channel 1: {:?}", message1), |
| 533 | /// message2 = watcher2.next() => println!("channel 2: {:?}", message2), |
| 534 | /// } |
| 535 | /// # } |
| 536 | /// ``` |
| 537 | /// |
| 538 | /// Note that due to the returned object borrowing the `self` reference, the borrow checker will |
| 539 | /// enforce only having a single of these returned objects at a time. Drop the previous message |
| 540 | /// before asking for the next one. That means this will not compile: |
| 541 | /// ```compile_fail |
| 542 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) { |
| 543 | /// let first = watcher.next(); |
| 544 | /// let second = watcher.next(); |
| 545 | /// first.await; |
| 546 | /// # } |
| 547 | /// ``` |
| 548 | /// and nor will this: |
| 549 | /// ```compile_fail |
| 550 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) { |
| 551 | /// let first = watcher.next().await; |
| 552 | /// watcher.next(); |
| 553 | /// println!("still have: {:?}", first); |
| 554 | /// # } |
| 555 | /// ``` |
| 556 | /// but this is fine: |
| 557 | /// ``` |
| 558 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) { |
| 559 | /// let first = watcher.next().await; |
| 560 | /// println!("have: {:?}", first); |
| 561 | /// watcher.next(); |
| 562 | /// # } |
| 563 | /// ``` |
| 564 | pub fn next(&mut self) -> RawWatcherNext { |
| 565 | RawWatcherNext(Some(self)) |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | /// The type returned from [`RawWatcher::next`], see there for details. |
| 570 | pub struct RawWatcherNext<'a>(Option<&'a mut RawWatcher>); |
| 571 | |
| 572 | impl<'a> Future for RawWatcherNext<'a> { |
| 573 | type Output = Context<'a>; |
| 574 | fn poll(mut self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<Context<'a>> { |
| 575 | let inner = self |
| 576 | .0 |
| 577 | .take() |
| 578 | .expect("May not call poll after it returns Ready"); |
| 579 | let maybe_context = inner.0.as_mut().PollNext(); |
| 580 | if maybe_context.is_null() { |
| 581 | // We're not returning a reference into it, so we can safely replace the reference to |
| 582 | // use again in the future. |
| 583 | self.0.replace(inner); |
| 584 | Poll::Pending |
| 585 | } else { |
| 586 | // SAFETY: We just checked if it's null. If not, it will be a valid pointer. It will |
| 587 | // remain a valid pointer for the borrow of the underlying `RawWatcher` (ie `'a`) |
| 588 | // because we're dropping `inner` (which is that reference), so it will need to be |
| 589 | // borrowed again which cannot happen before the end of `'a`. |
| 590 | Poll::Ready(Context(unsafe { &*maybe_context })) |
| 591 | } |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | impl FusedFuture for RawWatcherNext<'_> { |
| 596 | fn is_terminated(&self) -> bool { |
| 597 | self.0.is_none() |
| 598 | } |
| 599 | } |
| 600 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 601 | /// Provides async blocking access to messages on a channel. This will return every message on the |
| 602 | /// channel, in order. |
| 603 | /// |
| 604 | /// Use [`EventLoopRuntime::make_watcher`] to create one of these. |
| 605 | /// |
| 606 | /// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical |
| 607 | /// reasons. See [`RawWatcher`]'s documentation for details. |
| 608 | pub struct Watcher<T>(RawWatcher, PhantomData<*mut T>) |
| 609 | where |
| 610 | for<'a> T: FollowWith<'a>, |
| 611 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>; |
| 612 | |
| 613 | impl<T> Watcher<T> |
| 614 | where |
| 615 | for<'a> T: FollowWith<'a>, |
| 616 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 617 | { |
| 618 | /// Returns a Future to await the next value. This can be canceled (ie dropped) at will, |
| 619 | /// without skipping any messages. |
| 620 | /// |
| 621 | /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You |
| 622 | /// will need to call this function again to get the succeeding message. |
| 623 | /// |
| 624 | /// # Examples |
| 625 | /// |
| 626 | /// The common use case is immediately awaiting the next message: |
| 627 | /// ``` |
| 628 | /// # use pong_rust_fbs::aos::examples::Pong; |
| 629 | /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) { |
| 630 | /// println!("received: {:?}", watcher.next().await); |
| 631 | /// # } |
| 632 | /// ``` |
| 633 | /// |
| 634 | /// You can also await the first message from any of a set of channels: |
| 635 | /// ``` |
| 636 | /// # use pong_rust_fbs::aos::examples::Pong; |
| 637 | /// # async fn select( |
| 638 | /// # mut watcher1: aos_events_event_loop_runtime::Watcher<Pong<'static>>, |
| 639 | /// # mut watcher2: aos_events_event_loop_runtime::Watcher<Pong<'static>>, |
| 640 | /// # ) { |
| 641 | /// futures::select! { |
| 642 | /// message1 = watcher1.next() => println!("channel 1: {:?}", message1), |
| 643 | /// message2 = watcher2.next() => println!("channel 2: {:?}", message2), |
| 644 | /// } |
| 645 | /// # } |
| 646 | /// ``` |
| 647 | /// |
| 648 | /// Note that due to the returned object borrowing the `self` reference, the borrow checker will |
| 649 | /// enforce only having a single of these returned objects at a time. Drop the previous message |
| 650 | /// before asking for the next one. That means this will not compile: |
| 651 | /// ```compile_fail |
| 652 | /// # use pong_rust_fbs::aos::examples::Pong; |
| 653 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) { |
| 654 | /// let first = watcher.next(); |
| 655 | /// let second = watcher.next(); |
| 656 | /// first.await; |
| 657 | /// # } |
| 658 | /// ``` |
| 659 | /// and nor will this: |
| 660 | /// ```compile_fail |
| 661 | /// # use pong_rust_fbs::aos::examples::Pong; |
| 662 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) { |
| 663 | /// let first = watcher.next().await; |
| 664 | /// watcher.next(); |
| 665 | /// println!("still have: {:?}", first); |
| 666 | /// # } |
| 667 | /// ``` |
| 668 | /// but this is fine: |
| 669 | /// ``` |
| 670 | /// # use pong_rust_fbs::aos::examples::Pong; |
| 671 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) { |
| 672 | /// let first = watcher.next().await; |
| 673 | /// println!("have: {:?}", first); |
| 674 | /// watcher.next(); |
| 675 | /// # } |
| 676 | /// ``` |
| 677 | pub fn next(&mut self) -> WatcherNext<'_, <T as FollowWith<'_>>::Inner> { |
| 678 | WatcherNext(self.0.next(), PhantomData) |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | /// The type returned from [`Watcher::next`], see there for details. |
| 683 | pub struct WatcherNext<'watcher, T>(RawWatcherNext<'watcher>, PhantomData<*mut T>) |
| 684 | where |
| 685 | T: Follow<'watcher> + 'watcher; |
| 686 | |
| 687 | impl<'watcher, T> Future for WatcherNext<'watcher, T> |
| 688 | where |
| 689 | T: Follow<'watcher> + 'watcher, |
| 690 | { |
| 691 | type Output = TypedContext<'watcher, T>; |
| 692 | |
| 693 | fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> { |
| 694 | Pin::new(&mut self.get_mut().0).poll(cx).map(|context| |
| 695 | // SAFETY: The Watcher this was created from verified that the channel is the |
| 696 | // right type, and the C++ guarantees that the buffer's type matches. |
| 697 | TypedContext(context, PhantomData)) |
| 698 | } |
| 699 | } |
| 700 | |
| 701 | impl<'watcher, T> FusedFuture for WatcherNext<'watcher, T> |
| 702 | where |
| 703 | T: Follow<'watcher> + 'watcher, |
| 704 | { |
| 705 | fn is_terminated(&self) -> bool { |
| 706 | self.0.is_terminated() |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | /// A wrapper around [`Context`] which exposes the flatbuffer message with the appropriate type. |
| 711 | pub struct TypedContext<'a, T>( |
| 712 | // SAFETY: This must have a message, and it must be a valid `T` flatbuffer. |
| 713 | Context<'a>, |
| 714 | PhantomData<*mut T>, |
| 715 | ) |
| 716 | where |
| 717 | T: Follow<'a> + 'a; |
| 718 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 719 | impl<'a, T> TypedContext<'a, T> |
| 720 | where |
| 721 | T: Follow<'a> + 'a, |
| 722 | { |
| 723 | pub fn message(&self) -> Option<T::Inner> { |
| 724 | self.0.data().map(|data| { |
| 725 | // SAFETY: C++ guarantees that this is a valid flatbuffer. We guarantee it's the right |
| 726 | // type based on invariants for our type. |
| 727 | unsafe { root_unchecked::<T>(data) } |
| 728 | }) |
| 729 | } |
| 730 | |
| 731 | pub fn monotonic_event_time(&self) -> MonotonicInstant { |
| 732 | self.0.monotonic_event_time() |
| 733 | } |
| 734 | pub fn monotonic_remote_time(&self) -> MonotonicInstant { |
| 735 | self.0.monotonic_remote_time() |
| 736 | } |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 737 | pub fn realtime_event_time(&self) -> RealtimeInstant { |
| 738 | self.0.realtime_event_time() |
| 739 | } |
| 740 | pub fn realtime_remote_time(&self) -> RealtimeInstant { |
| 741 | self.0.realtime_remote_time() |
| 742 | } |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 743 | pub fn queue_index(&self) -> u32 { |
| 744 | self.0.queue_index() |
| 745 | } |
| 746 | pub fn remote_queue_index(&self) -> u32 { |
| 747 | self.0.remote_queue_index() |
| 748 | } |
| 749 | pub fn buffer_index(&self) -> i32 { |
| 750 | self.0.buffer_index() |
| 751 | } |
| 752 | pub fn source_boot_uuid(&self) -> &Uuid { |
| 753 | self.0.source_boot_uuid() |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | impl<'a, T> fmt::Debug for TypedContext<'a, T> |
| 758 | where |
| 759 | T: Follow<'a> + 'a, |
| 760 | T::Inner: fmt::Debug, |
| 761 | { |
| 762 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 763 | f.debug_struct("TypedContext") |
| 764 | .field("monotonic_event_time", &self.monotonic_event_time()) |
| 765 | .field("monotonic_remote_time", &self.monotonic_remote_time()) |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 766 | .field("realtime_event_time", &self.realtime_event_time()) |
| 767 | .field("realtime_remote_time", &self.realtime_remote_time()) |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 768 | .field("queue_index", &self.queue_index()) |
| 769 | .field("remote_queue_index", &self.remote_queue_index()) |
| 770 | .field("message", &self.message()) |
| 771 | .field("buffer_index", &self.buffer_index()) |
| 772 | .field("source_boot_uuid", &self.source_boot_uuid()) |
| 773 | .finish() |
| 774 | } |
| 775 | } |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 776 | |
| 777 | /// Provides access to messages on a channel, without the ability to wait for a new one. This |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 778 | /// provides APIs to get the latest message, and to follow along and retrieve each message in order. |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 779 | /// |
| 780 | /// Use [`EventLoopRuntime::make_raw_fetcher`] to create one of these. |
| 781 | /// |
| 782 | /// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs |
| 783 | /// for actually interpreting messages. You probably want a [`Fetcher`] instead. |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 784 | // SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL). |
| 785 | #[repr(transparent)] |
| 786 | pub struct RawFetcher(Pin<Box<ffi::aos::FetcherForRust>>); |
| 787 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 788 | impl RawFetcher { |
| 789 | pub fn fetch_next(&mut self) -> bool { |
| 790 | self.0.as_mut().FetchNext() |
| 791 | } |
| 792 | |
| 793 | pub fn fetch(&mut self) -> bool { |
| 794 | self.0.as_mut().Fetch() |
| 795 | } |
| 796 | |
| 797 | pub fn context(&self) -> Context { |
| 798 | Context(self.0.context()) |
| 799 | } |
| 800 | } |
| 801 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 802 | /// Provides access to messages on a channel, without the ability to wait for a new one. This |
| 803 | /// provides APIs to get the latest message, and to follow along and retrieve each message in order. |
| 804 | /// |
| 805 | /// Use [`EventLoopRuntime::make_fetcher`] to create one of these. |
| 806 | pub struct Fetcher<T>( |
| 807 | // SAFETY: This must produce messages of type `T`. |
| 808 | RawFetcher, |
| 809 | PhantomData<*mut T>, |
| 810 | ) |
| 811 | where |
| 812 | for<'a> T: FollowWith<'a>, |
| 813 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>; |
| 814 | |
| 815 | impl<T> Fetcher<T> |
| 816 | where |
| 817 | for<'a> T: FollowWith<'a>, |
| 818 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 819 | { |
| 820 | pub fn fetch_next(&mut self) -> bool { |
| 821 | self.0.fetch_next() |
| 822 | } |
| 823 | pub fn fetch(&mut self) -> bool { |
| 824 | self.0.fetch() |
| 825 | } |
| 826 | |
| 827 | pub fn context(&self) -> TypedContext<'_, <T as FollowWith<'_>>::Inner> { |
| 828 | // SAFETY: We verified that this is the correct type, and C++ guarantees that the buffer's |
| 829 | // type matches. |
| 830 | TypedContext(self.0.context(), PhantomData) |
| 831 | } |
| 832 | } |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 833 | |
| 834 | /// Allows sending messages on a channel. |
| 835 | /// |
| 836 | /// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs |
| 837 | /// for actually creating messages to send. You probably want a [`Sender`] instead. |
| 838 | /// |
| 839 | /// Use [`EventLoopRuntime::make_raw_sender`] to create one of these. |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 840 | // SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL). |
| 841 | #[repr(transparent)] |
| 842 | pub struct RawSender(Pin<Box<ffi::aos::SenderForRust>>); |
| 843 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 844 | impl RawSender { |
| 845 | fn buffer(&mut self) -> &mut [u8] { |
| 846 | // SAFETY: This is a valid slice, and `u8` doesn't have any alignment requirements. |
| 847 | unsafe { slice::from_raw_parts_mut(self.0.as_mut().data(), self.0.as_mut().size()) } |
| 848 | } |
| 849 | |
| 850 | /// Returns an object which can be used to build a message. |
| 851 | /// |
| 852 | /// # Examples |
| 853 | /// |
| 854 | /// ``` |
| 855 | /// # use pong_rust_fbs::aos::examples::PongBuilder; |
| 856 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) { |
| 857 | /// # unsafe { |
| 858 | /// let mut builder = sender.make_builder(); |
| 859 | /// let pong = PongBuilder::new(builder.fbb()).finish(); |
| 860 | /// builder.send(pong); |
| 861 | /// # } |
| 862 | /// # } |
| 863 | /// ``` |
| 864 | /// |
| 865 | /// You can bail out of building a message and build another one: |
| 866 | /// ``` |
| 867 | /// # use pong_rust_fbs::aos::examples::PongBuilder; |
| 868 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) { |
| 869 | /// # unsafe { |
| 870 | /// let mut builder1 = sender.make_builder(); |
| 871 | /// builder1.fbb(); |
| 872 | /// let mut builder2 = sender.make_builder(); |
| 873 | /// let pong = PongBuilder::new(builder2.fbb()).finish(); |
| 874 | /// builder2.send(pong); |
| 875 | /// # } |
| 876 | /// # } |
| 877 | /// ``` |
| 878 | /// but you cannot build two messages at the same time with a single builder: |
| 879 | /// ```compile_fail |
| 880 | /// # use pong_rust_fbs::aos::examples::PongBuilder; |
| 881 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) { |
| 882 | /// # unsafe { |
| 883 | /// let mut builder1 = sender.make_builder(); |
| 884 | /// let mut builder2 = sender.make_builder(); |
| 885 | /// PongBuilder::new(builder2.fbb()).finish(); |
| 886 | /// PongBuilder::new(builder1.fbb()).finish(); |
| 887 | /// # } |
| 888 | /// # } |
| 889 | /// ``` |
| 890 | pub fn make_builder(&mut self) -> RawBuilder { |
| 891 | // TODO(Brian): Actually use the provided buffer instead of just using its |
| 892 | // size to allocate a separate one. |
| 893 | // |
| 894 | // See https://github.com/google/flatbuffers/issues/7385. |
| 895 | let fbb = flatbuffers::FlatBufferBuilder::with_capacity(self.buffer().len()); |
| 896 | RawBuilder { |
| 897 | raw_sender: self, |
| 898 | fbb, |
| 899 | } |
| 900 | } |
| 901 | } |
| 902 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 903 | /// Used for building a message. See [`RawSender::make_builder`] for details. |
| 904 | pub struct RawBuilder<'sender> { |
| 905 | raw_sender: &'sender mut RawSender, |
| 906 | fbb: flatbuffers::FlatBufferBuilder<'sender>, |
| 907 | } |
| 908 | |
| 909 | impl<'sender> RawBuilder<'sender> { |
| 910 | pub fn fbb(&mut self) -> &mut flatbuffers::FlatBufferBuilder<'sender> { |
| 911 | &mut self.fbb |
| 912 | } |
| 913 | |
| 914 | /// # Safety |
| 915 | /// |
| 916 | /// `T` must match the type of the channel of the sender this builder was created from. |
| 917 | pub unsafe fn send<T>(mut self, root: flatbuffers::WIPOffset<T>) -> Result<(), SendError> { |
| 918 | self.fbb.finish_minimal(root); |
| 919 | let data = self.fbb.finished_data(); |
| 920 | |
| 921 | use ffi::aos::RawSender_Error as FfiError; |
| 922 | // SAFETY: This is a valid buffer we're passing. |
| 923 | match unsafe { |
| 924 | self.raw_sender |
| 925 | .0 |
| 926 | .as_mut() |
| 927 | .CopyAndSend(data.as_ptr(), data.len()) |
| 928 | } { |
| 929 | FfiError::kOk => Ok(()), |
| 930 | FfiError::kMessagesSentTooFast => Err(SendError::MessagesSentTooFast), |
| 931 | FfiError::kInvalidRedzone => Err(SendError::InvalidRedzone), |
| 932 | } |
| 933 | } |
| 934 | } |
| 935 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 936 | /// Allows sending messages on a channel with a type-safe API. |
| 937 | /// |
| 938 | /// Use [`EventLoopRuntime::make_raw_sender`] to create one of these. |
| 939 | pub struct Sender<T>( |
| 940 | // SAFETY: This must accept messages of type `T`. |
| 941 | RawSender, |
| 942 | PhantomData<*mut T>, |
| 943 | ) |
| 944 | where |
| 945 | for<'a> T: FollowWith<'a>, |
| 946 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>; |
| 947 | |
| 948 | impl<T> Sender<T> |
| 949 | where |
| 950 | for<'a> T: FollowWith<'a>, |
| 951 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 952 | { |
| 953 | /// Returns an object which can be used to build a message. |
| 954 | /// |
| 955 | /// # Examples |
| 956 | /// |
| 957 | /// ``` |
| 958 | /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder}; |
| 959 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) { |
| 960 | /// let mut builder = sender.make_builder(); |
| 961 | /// let pong = PongBuilder::new(builder.fbb()).finish(); |
| 962 | /// builder.send(pong); |
| 963 | /// # } |
| 964 | /// ``` |
| 965 | /// |
| 966 | /// You can bail out of building a message and build another one: |
| 967 | /// ``` |
| 968 | /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder}; |
| 969 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) { |
| 970 | /// let mut builder1 = sender.make_builder(); |
| 971 | /// builder1.fbb(); |
| 972 | /// let mut builder2 = sender.make_builder(); |
| 973 | /// let pong = PongBuilder::new(builder2.fbb()).finish(); |
| 974 | /// builder2.send(pong); |
| 975 | /// # } |
| 976 | /// ``` |
| 977 | /// but you cannot build two messages at the same time with a single builder: |
| 978 | /// ```compile_fail |
| 979 | /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder}; |
| 980 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) { |
| 981 | /// let mut builder1 = sender.make_builder(); |
| 982 | /// let mut builder2 = sender.make_builder(); |
| 983 | /// PongBuilder::new(builder2.fbb()).finish(); |
| 984 | /// PongBuilder::new(builder1.fbb()).finish(); |
| 985 | /// # } |
| 986 | /// ``` |
| 987 | pub fn make_builder(&mut self) -> Builder<T> { |
| 988 | Builder(self.0.make_builder(), PhantomData) |
| 989 | } |
| 990 | } |
| 991 | |
| 992 | /// Used for building a message. See [`Sender::make_builder`] for details. |
| 993 | pub struct Builder<'sender, T>( |
| 994 | // SAFETY: This must accept messages of type `T`. |
| 995 | RawBuilder<'sender>, |
| 996 | PhantomData<*mut T>, |
| 997 | ) |
| 998 | where |
| 999 | for<'a> T: FollowWith<'a>, |
| 1000 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>; |
| 1001 | |
| 1002 | impl<'sender, T> Builder<'sender, T> |
| 1003 | where |
| 1004 | for<'a> T: FollowWith<'a>, |
| 1005 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 1006 | { |
| 1007 | pub fn fbb(&mut self) -> &mut flatbuffers::FlatBufferBuilder<'sender> { |
| 1008 | self.0.fbb() |
| 1009 | } |
| 1010 | |
| 1011 | pub fn send<'a>( |
| 1012 | self, |
| 1013 | root: flatbuffers::WIPOffset<<T as FollowWith<'a>>::Inner>, |
| 1014 | ) -> Result<(), SendError> { |
| 1015 | // SAFETY: We guarantee this is the right type based on invariants for our type. |
| 1016 | unsafe { self.0.send(root) } |
| 1017 | } |
| 1018 | } |
| 1019 | |
| 1020 | #[derive(Clone, Copy, Eq, PartialEq, Debug, Error)] |
| 1021 | pub enum SendError { |
| 1022 | #[error("messages have been sent too fast on this channel")] |
| 1023 | MessagesSentTooFast, |
| 1024 | #[error("invalid redzone data, shared memory corruption detected")] |
| 1025 | InvalidRedzone, |
| 1026 | } |
| 1027 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1028 | #[repr(transparent)] |
| 1029 | #[derive(Clone, Copy)] |
| 1030 | pub struct Context<'context>(&'context ffi::aos::Context); |
| 1031 | |
| 1032 | impl fmt::Debug for Context<'_> { |
| 1033 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1034 | f.debug_struct("Context") |
| 1035 | .field("monotonic_event_time", &self.monotonic_event_time()) |
| 1036 | .field("monotonic_remote_time", &self.monotonic_remote_time()) |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 1037 | .field("realtime_event_time", &self.realtime_event_time()) |
| 1038 | .field("realtime_remote_time", &self.realtime_remote_time()) |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1039 | .field("queue_index", &self.queue_index()) |
| 1040 | .field("remote_queue_index", &self.remote_queue_index()) |
| 1041 | .field("size", &self.data().map(|data| data.len())) |
| 1042 | .field("buffer_index", &self.buffer_index()) |
| 1043 | .field("source_boot_uuid", &self.source_boot_uuid()) |
| 1044 | .finish() |
| 1045 | } |
| 1046 | } |
| 1047 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1048 | impl<'context> Context<'context> { |
| 1049 | pub fn monotonic_event_time(self) -> MonotonicInstant { |
| 1050 | MonotonicInstant(self.0.monotonic_event_time) |
| 1051 | } |
| 1052 | |
| 1053 | pub fn monotonic_remote_time(self) -> MonotonicInstant { |
| 1054 | MonotonicInstant(self.0.monotonic_remote_time) |
| 1055 | } |
| 1056 | |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 1057 | pub fn realtime_event_time(self) -> RealtimeInstant { |
| 1058 | RealtimeInstant(self.0.realtime_event_time) |
| 1059 | } |
| 1060 | |
| 1061 | pub fn realtime_remote_time(self) -> RealtimeInstant { |
| 1062 | RealtimeInstant(self.0.realtime_remote_time) |
| 1063 | } |
| 1064 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1065 | pub fn queue_index(self) -> u32 { |
| 1066 | self.0.queue_index |
| 1067 | } |
| 1068 | pub fn remote_queue_index(self) -> u32 { |
| 1069 | self.0.remote_queue_index |
| 1070 | } |
| 1071 | |
| 1072 | pub fn data(self) -> Option<&'context [u8]> { |
| 1073 | if self.0.data.is_null() { |
| 1074 | None |
| 1075 | } else { |
| 1076 | // SAFETY: |
| 1077 | // * `u8` has no alignment requirements |
| 1078 | // * It must be a single initialized flatbuffers buffer |
| 1079 | // * The borrow in `self.0` guarantees it won't be modified for `'context` |
| 1080 | Some(unsafe { slice::from_raw_parts(self.0.data as *const u8, self.0.size) }) |
| 1081 | } |
| 1082 | } |
| 1083 | |
| 1084 | pub fn buffer_index(self) -> i32 { |
| 1085 | self.0.buffer_index |
| 1086 | } |
| 1087 | |
| 1088 | pub fn source_boot_uuid(self) -> &'context Uuid { |
| 1089 | // SAFETY: `self` has a valid C++ object. C++ guarantees that the return value will be |
| 1090 | // valid until something changes the context, which is `'context`. |
| 1091 | Uuid::from_bytes_ref(&self.0.source_boot_uuid) |
| 1092 | } |
| 1093 | } |
| 1094 | |
Brian Silverman | 76f4836 | 2022-08-24 21:09:08 -0700 | [diff] [blame] | 1095 | /// The type returned from [`EventLoopRuntime::on_run`], see there for details. |
| 1096 | // SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL). |
| 1097 | #[repr(transparent)] |
| 1098 | pub struct OnRun(Pin<Box<ffi::aos::OnRunForRust>>); |
| 1099 | |
| 1100 | impl Future for OnRun { |
| 1101 | type Output = (); |
| 1102 | |
| 1103 | fn poll(self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<()> { |
| 1104 | if self.0.is_running() { |
| 1105 | Poll::Ready(()) |
| 1106 | } else { |
| 1107 | Poll::Pending |
| 1108 | } |
| 1109 | } |
| 1110 | } |
| 1111 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1112 | /// Represents a `aos::monotonic_clock::time_point` in a natural Rust way. This |
| 1113 | /// is intended to have the same API as [`std::time::Instant`], any missing |
| 1114 | /// functionality can be added if useful. |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1115 | #[repr(transparent)] |
| 1116 | #[derive(Clone, Copy, Eq, PartialEq)] |
| 1117 | pub struct MonotonicInstant(i64); |
| 1118 | |
| 1119 | impl MonotonicInstant { |
| 1120 | /// `aos::monotonic_clock::min_time`, commonly used as a sentinel value. |
| 1121 | pub const MIN_TIME: Self = Self(i64::MIN); |
| 1122 | |
| 1123 | pub fn is_min_time(self) -> bool { |
| 1124 | self == Self::MIN_TIME |
| 1125 | } |
| 1126 | |
| 1127 | pub fn duration_since_epoch(self) -> Option<Duration> { |
| 1128 | if self.is_min_time() { |
| 1129 | None |
| 1130 | } else { |
| 1131 | Some(Duration::from_nanos(self.0.try_into().expect( |
| 1132 | "monotonic_clock::time_point should always be after the epoch", |
| 1133 | ))) |
| 1134 | } |
| 1135 | } |
| 1136 | } |
| 1137 | |
| 1138 | impl fmt::Debug for MonotonicInstant { |
| 1139 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 1140 | self.duration_since_epoch().fmt(f) |
| 1141 | } |
| 1142 | } |
| 1143 | |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 1144 | #[repr(transparent)] |
| 1145 | #[derive(Clone, Copy, Eq, PartialEq)] |
| 1146 | pub struct RealtimeInstant(i64); |
| 1147 | |
| 1148 | impl RealtimeInstant { |
| 1149 | pub const MIN_TIME: Self = Self(i64::MIN); |
| 1150 | |
| 1151 | pub fn is_min_time(self) -> bool { |
| 1152 | self == Self::MIN_TIME |
| 1153 | } |
| 1154 | |
| 1155 | pub fn duration_since_epoch(self) -> Option<Duration> { |
| 1156 | if self.is_min_time() { |
| 1157 | None |
| 1158 | } else { |
| 1159 | Some(Duration::from_nanos(self.0.try_into().expect( |
| 1160 | "monotonic_clock::time_point should always be after the epoch", |
| 1161 | ))) |
| 1162 | } |
| 1163 | } |
| 1164 | } |
| 1165 | |
| 1166 | impl fmt::Debug for RealtimeInstant { |
| 1167 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 1168 | self.duration_since_epoch().fmt(f) |
| 1169 | } |
| 1170 | } |
| 1171 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1172 | mod panic_waker { |
| 1173 | use std::task::{RawWaker, RawWakerVTable, Waker}; |
| 1174 | |
| 1175 | unsafe fn clone_panic_waker(_data: *const ()) -> RawWaker { |
| 1176 | raw_panic_waker() |
| 1177 | } |
| 1178 | |
| 1179 | unsafe fn noop(_data: *const ()) {} |
| 1180 | |
| 1181 | unsafe fn wake_panic(_data: *const ()) { |
| 1182 | panic!("Nothing should wake EventLoopRuntime's waker"); |
| 1183 | } |
| 1184 | |
| 1185 | const PANIC_WAKER_VTABLE: RawWakerVTable = |
| 1186 | RawWakerVTable::new(clone_panic_waker, wake_panic, wake_panic, noop); |
| 1187 | |
| 1188 | fn raw_panic_waker() -> RawWaker { |
| 1189 | RawWaker::new(std::ptr::null(), &PANIC_WAKER_VTABLE) |
| 1190 | } |
| 1191 | |
| 1192 | pub fn panic_waker() -> Waker { |
| 1193 | // SAFETY: The implementations of the RawWakerVTable functions do what is required of them. |
| 1194 | unsafe { Waker::from_raw(raw_panic_waker()) } |
| 1195 | } |
| 1196 | } |
| 1197 | |
| 1198 | use panic_waker::panic_waker; |
Adam Snaider | 163800b | 2023-07-12 00:21:17 -0400 | [diff] [blame] | 1199 | |
| 1200 | pub struct ExitHandle(UniquePtr<CppExitHandle>); |
| 1201 | |
| 1202 | impl ExitHandle { |
| 1203 | /// Exits the EventLoops represented by this handle. You probably want to immediately return |
| 1204 | /// from the context this is called in. Awaiting [`exit`] instead of using this function is an |
| 1205 | /// easy way to do that. |
| 1206 | pub fn exit_sync(mut self) { |
| 1207 | self.0.as_mut().unwrap().Exit(); |
| 1208 | } |
| 1209 | |
| 1210 | /// Exits the EventLoops represented by this handle, and never returns. Immediately awaiting |
| 1211 | /// this from a [`EventLoopRuntime::spawn`]ed task is usually what you want, it will ensure |
| 1212 | /// that no more code from that task runs. |
| 1213 | pub async fn exit(self) -> Never { |
| 1214 | self.exit_sync(); |
| 1215 | pending().await |
| 1216 | } |
| 1217 | } |
| 1218 | |
| 1219 | impl From<UniquePtr<CppExitHandle>> for ExitHandle { |
| 1220 | fn from(inner: UniquePtr<ffi::aos::ExitHandle>) -> Self { |
| 1221 | Self(inner) |
| 1222 | } |
| 1223 | } |