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 | |
| 47 | use std::{fmt, future::Future, marker::PhantomData, pin::Pin, slice, task::Poll, time::Duration}; |
| 48 | |
| 49 | use autocxx::{ |
| 50 | subclass::{is_subclass, CppSubclass}, |
| 51 | WithinBox, |
| 52 | }; |
| 53 | use cxx::UniquePtr; |
| 54 | use futures::{future::FusedFuture, never::Never}; |
| 55 | use thiserror::Error; |
| 56 | use uuid::Uuid; |
| 57 | |
| 58 | pub use aos_configuration::{Channel, ChannelLookupError, Configuration, ConfigurationExt, Node}; |
| 59 | pub use aos_uuid::UUID; |
| 60 | |
| 61 | autocxx::include_cpp! ( |
| 62 | #include "aos/events/event_loop_runtime.h" |
| 63 | |
| 64 | safety!(unsafe) |
| 65 | |
| 66 | generate_pod!("aos::Context") |
| 67 | generate!("aos::WatcherForRust") |
| 68 | generate!("aos::RawSender_Error") |
| 69 | generate!("aos::SenderForRust") |
| 70 | generate!("aos::FetcherForRust") |
| 71 | generate!("aos::EventLoopRuntime") |
| 72 | |
| 73 | subclass!("aos::ApplicationFuture", RustApplicationFuture) |
| 74 | |
| 75 | extern_cpp_type!("aos::Configuration", crate::Configuration) |
| 76 | extern_cpp_type!("aos::Channel", crate::Channel) |
| 77 | extern_cpp_type!("aos::Node", crate::Node) |
| 78 | extern_cpp_type!("aos::UUID", crate::UUID) |
| 79 | ); |
| 80 | |
| 81 | pub type EventLoop = ffi::aos::EventLoop; |
| 82 | |
| 83 | /// # Safety |
| 84 | /// |
| 85 | /// This should have a `'event_loop` lifetime and `future` should include that in its type, but |
| 86 | /// autocxx's subclass doesn't support that. Even if it did, it wouldn't be enforced. C++ is |
| 87 | /// enforcing the lifetime: it destroys this object along with the C++ `EventLoopRuntime`, which |
| 88 | /// must be outlived by the EventLoop. |
| 89 | #[doc(hidden)] |
| 90 | #[is_subclass(superclass("aos::ApplicationFuture"))] |
| 91 | pub struct RustApplicationFuture { |
| 92 | /// This logically has a `'event_loop` bound, see the class comment for details. |
| 93 | future: Pin<Box<dyn Future<Output = Never>>>, |
| 94 | } |
| 95 | |
| 96 | impl ffi::aos::ApplicationFuture_methods for RustApplicationFuture { |
| 97 | fn Poll(&mut self) { |
| 98 | // This is always allowed because it can never create a value of type `Ready<Never>` to |
| 99 | // return, so it must always return `Pending`. That also means the value it returns doesn't |
| 100 | // mean anything, so we ignore it. |
| 101 | let _ = |
| 102 | Pin::new(&mut self.future).poll(&mut std::task::Context::from_waker(&panic_waker())); |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | impl RustApplicationFuture { |
| 107 | pub fn new<'event_loop>( |
| 108 | future: impl Future<Output = Never> + 'event_loop, |
| 109 | ) -> UniquePtr<ffi::aos::ApplicationFuture> { |
| 110 | /// # Safety |
| 111 | /// |
| 112 | /// This completely removes the `'event_loop` lifetime, the caller must ensure that is |
| 113 | /// sound. |
| 114 | unsafe fn remove_lifetime<'event_loop>( |
| 115 | future: Pin<Box<dyn Future<Output = Never> + 'event_loop>>, |
| 116 | ) -> Pin<Box<dyn Future<Output = Never>>> { |
| 117 | // SAFETY: Caller is responsible. |
| 118 | unsafe { std::mem::transmute(future) } |
| 119 | } |
| 120 | |
| 121 | Self::as_ApplicationFuture_unique_ptr(Self::new_cpp_owned(Self { |
| 122 | // SAFETY: C++ manages observing the lifetime, see [`RustApplicationFuture`] for |
| 123 | // details. |
| 124 | future: unsafe { remove_lifetime(Box::pin(future)) }, |
| 125 | cpp_peer: Default::default(), |
| 126 | })) |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | pub struct EventLoopRuntime<'event_loop>( |
| 131 | Pin<Box<ffi::aos::EventLoopRuntime>>, |
| 132 | // This is the lifetime of the underlying EventLoop, which is held in C++ via `.0`. |
| 133 | PhantomData<&'event_loop mut ()>, |
| 134 | ); |
| 135 | |
| 136 | /// Manages the Rust interface to a *single* `aos::EventLoop`. This is intended to be used by a |
| 137 | /// single application. |
| 138 | impl<'event_loop> EventLoopRuntime<'event_loop> { |
| 139 | /// Creates a new runtime. This must be the only user of the underlying `aos::EventLoop`, or |
| 140 | /// things may panic unexpectedly. |
| 141 | /// |
| 142 | /// Call [`spawn`] to respond to events. The non-event-driven APIs may be used without calling |
| 143 | /// this. |
| 144 | /// |
| 145 | /// This is an async runtime, but it's a somewhat unusual one. See the module-level |
| 146 | /// documentation for details. |
| 147 | /// |
| 148 | /// # Safety |
| 149 | /// |
| 150 | /// `event_loop` must be valid for `'event_loop`. Effectively we want the argument to be |
| 151 | /// `&'event_loop mut EventLoop`, but we can't do that (see the module-level documentation for |
| 152 | /// details). |
| 153 | /// |
| 154 | /// This is a tricky thing to guarantee, be very cautious calling this function. It's an unbound |
| 155 | /// lifetime so you should probably wrap it in a function that directly attaches a known |
| 156 | /// lifetime. One common pattern is calling this in the constructor of an object whose lifetime |
| 157 | /// is managed by C++; C++ doesn't inherit the Rust lifetime but we do have a lot of C++ code |
| 158 | /// that obeys the rule of destroying the object before the EventLoop, which is equivalent to |
| 159 | /// this restriction. |
| 160 | /// |
| 161 | /// In Rust terms, this is equivalent to storing `event_loop` in the returned object, which |
| 162 | /// will dereference it throughout its lifetime, and the caller must guarantee this is sound. |
| 163 | pub unsafe fn new(event_loop: *mut ffi::aos::EventLoop) -> Self { |
| 164 | Self( |
| 165 | // SAFETY: We push all the validity requirements for this up to our caller. |
| 166 | unsafe { ffi::aos::EventLoopRuntime::new(event_loop) }.within_box(), |
| 167 | PhantomData, |
| 168 | ) |
| 169 | } |
| 170 | |
| 171 | /// Returns the pointer passed into the constructor. |
| 172 | /// |
| 173 | /// The returned value should only be used for destroying it (_after_ `self` is dropped) or |
| 174 | /// calling other C++ APIs. |
| 175 | pub fn raw_event_loop(&mut self) -> *mut ffi::aos::EventLoop { |
| 176 | self.0.as_mut().event_loop() |
| 177 | } |
| 178 | |
| 179 | // TODO(Brian): Expose `name`. Need to sort out the lifetimes. C++ can reallocate the pointer |
| 180 | // independent of Rust. Use it in `get_raw_channel` instead of passing the name in. |
| 181 | |
| 182 | pub fn get_raw_channel( |
| 183 | &self, |
| 184 | name: &str, |
| 185 | typename: &str, |
| 186 | application_name: &str, |
| 187 | ) -> Result<&'event_loop Channel, ChannelLookupError> { |
| 188 | self.configuration() |
| 189 | .get_channel(name, typename, application_name, self.node()) |
| 190 | } |
| 191 | |
| 192 | // TODO(Brian): `get_channel<T>`. |
| 193 | |
| 194 | /// Starts running the given `task`, which may not return (as specified by its type). If you |
| 195 | /// want your task to stop, return the result of awaiting [`futures::future::pending`], which |
| 196 | /// will never complete. `task` will not be polled after the underlying `aos::EventLoop` exits. |
| 197 | /// |
| 198 | /// TODO(Brian): Make this paragraph true: |
| 199 | /// Note that task will be polled immediately. If you want to defer work until the event loop |
| 200 | /// starts running, await TODO in the task. |
| 201 | /// |
| 202 | /// # Panics |
| 203 | /// |
| 204 | /// Panics if called more than once. See the module-level documentation for alternatives if you |
| 205 | /// want to do this. |
| 206 | /// |
| 207 | /// # Examples with interesting return types |
| 208 | /// |
| 209 | /// These are all valid futures which never return: |
| 210 | /// ``` |
| 211 | /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) { |
| 212 | /// # use futures::{never::Never, future::pending}; |
| 213 | /// async fn pending_wrapper() -> Never { |
| 214 | /// pending().await |
| 215 | /// } |
| 216 | /// async fn loop_forever() -> Never { |
| 217 | /// loop {} |
| 218 | /// } |
| 219 | /// |
| 220 | /// runtime.spawn(pending()); |
| 221 | /// runtime.spawn(async { pending().await }); |
| 222 | /// runtime.spawn(pending_wrapper()); |
| 223 | /// runtime.spawn(async { loop {} }); |
| 224 | /// runtime.spawn(loop_forever()); |
| 225 | /// runtime.spawn(async { println!("all done"); pending().await }); |
| 226 | /// # } |
| 227 | /// ``` |
| 228 | /// but this is not: |
| 229 | /// ```compile_fail |
| 230 | /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) { |
| 231 | /// # use futures::ready; |
| 232 | /// runtime.spawn(ready()); |
| 233 | /// # } |
| 234 | /// ``` |
| 235 | /// and neither is this: |
| 236 | /// ```compile_fail |
| 237 | /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) { |
| 238 | /// # use futures::ready; |
| 239 | /// runtime.spawn(async { println!("all done") }); |
| 240 | /// # } |
| 241 | /// ``` |
| 242 | /// |
| 243 | /// # Examples with capturing |
| 244 | /// |
| 245 | /// The future can capture things. This is important to access other objects created from the |
| 246 | /// runtime, either before calling this function: |
| 247 | /// ``` |
| 248 | /// # fn compile_check<'event_loop>( |
| 249 | /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>, |
| 250 | /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel, |
| 251 | /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel, |
| 252 | /// # ) { |
| 253 | /// let mut watcher1 = runtime.make_raw_watcher(channel1); |
| 254 | /// let mut watcher2 = runtime.make_raw_watcher(channel2); |
| 255 | /// runtime.spawn(async move { loop { |
| 256 | /// watcher1.next().await; |
| 257 | /// watcher2.next().await; |
| 258 | /// }}); |
| 259 | /// # } |
| 260 | /// ``` |
| 261 | /// or after: |
| 262 | /// ``` |
| 263 | /// # fn compile_check<'event_loop>( |
| 264 | /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>, |
| 265 | /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel, |
| 266 | /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel, |
| 267 | /// # ) { |
| 268 | /// # use std::{cell::RefCell, rc::Rc}; |
| 269 | /// let runtime = Rc::new(RefCell::new(runtime)); |
| 270 | /// runtime.borrow_mut().spawn({ |
| 271 | /// let mut runtime = runtime.clone(); |
| 272 | /// async move { |
| 273 | /// let mut runtime = runtime.borrow_mut(); |
| 274 | /// let mut watcher1 = runtime.make_raw_watcher(channel1); |
| 275 | /// let mut watcher2 = runtime.make_raw_watcher(channel2); |
| 276 | /// loop { |
| 277 | /// watcher1.next().await; |
| 278 | /// watcher2.next().await; |
| 279 | /// } |
| 280 | /// } |
| 281 | /// }); |
| 282 | /// # } |
| 283 | /// ``` |
| 284 | /// or both: |
| 285 | /// ``` |
| 286 | /// # fn compile_check<'event_loop>( |
| 287 | /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>, |
| 288 | /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel, |
| 289 | /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel, |
| 290 | /// # ) { |
| 291 | /// # use std::{cell::RefCell, rc::Rc}; |
| 292 | /// let mut watcher1 = runtime.make_raw_watcher(channel1); |
| 293 | /// let runtime = Rc::new(RefCell::new(runtime)); |
| 294 | /// runtime.borrow_mut().spawn({ |
| 295 | /// let mut runtime = runtime.clone(); |
| 296 | /// async move { |
| 297 | /// let mut runtime = runtime.borrow_mut(); |
| 298 | /// let mut watcher2 = runtime.make_raw_watcher(channel2); |
| 299 | /// loop { |
| 300 | /// watcher1.next().await; |
| 301 | /// watcher2.next().await; |
| 302 | /// } |
| 303 | /// } |
| 304 | /// }); |
| 305 | /// # } |
| 306 | /// ``` |
| 307 | /// |
| 308 | /// But you cannot capture local variables: |
| 309 | /// ```compile_fail |
| 310 | /// # fn compile_check<'event_loop>( |
| 311 | /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>, |
| 312 | /// # ) { |
| 313 | /// let mut local: i32 = 971; |
| 314 | /// let local = &mut local; |
| 315 | /// runtime.spawn(async move { loop { |
| 316 | /// println!("have: {}", local); |
| 317 | /// }}); |
| 318 | /// # } |
| 319 | /// ``` |
| 320 | pub fn spawn(&mut self, task: impl Future<Output = Never> + 'event_loop) { |
| 321 | self.0.as_mut().spawn(RustApplicationFuture::new(task)); |
| 322 | } |
| 323 | |
| 324 | pub fn configuration(&self) -> &'event_loop Configuration { |
| 325 | // SAFETY: It's always a pointer valid for longer than the underlying EventLoop. |
| 326 | unsafe { &*self.0.configuration() } |
| 327 | } |
| 328 | |
| 329 | pub fn node(&self) -> Option<&'event_loop Node> { |
| 330 | // SAFETY: It's always a pointer valid for longer than the underlying EventLoop, or null. |
| 331 | unsafe { self.0.node().as_ref() } |
| 332 | } |
| 333 | |
| 334 | pub fn monotonic_now(&self) -> MonotonicInstant { |
| 335 | MonotonicInstant(self.0.monotonic_now()) |
| 336 | } |
| 337 | |
| 338 | /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is |
| 339 | /// part of `self.configuration()`, which will always have this lifetime. |
| 340 | /// |
| 341 | /// # Panics |
| 342 | /// |
| 343 | /// Dropping `self` before the returned object is dropped will panic. |
| 344 | pub fn make_raw_watcher(&mut self, channel: &'event_loop Channel) -> RawWatcher { |
| 345 | // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under |
| 346 | // the usual autocxx heuristics. |
| 347 | RawWatcher(unsafe { self.0.as_mut().MakeWatcher(channel) }.within_box()) |
| 348 | } |
| 349 | |
| 350 | /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is |
| 351 | /// part of `self.configuration()`, which will always have this lifetime. |
| 352 | /// |
| 353 | /// # Panics |
| 354 | /// |
| 355 | /// Dropping `self` before the returned object is dropped will panic. |
| 356 | pub fn make_raw_sender(&mut self, channel: &'event_loop Channel) -> RawSender { |
| 357 | // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under |
| 358 | // the usual autocxx heuristics. |
| 359 | RawSender(unsafe { self.0.as_mut().MakeSender(channel) }.within_box()) |
| 360 | } |
| 361 | |
| 362 | /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is |
| 363 | /// part of `self.configuration()`, which will always have this lifetime. |
| 364 | /// |
| 365 | /// # Panics |
| 366 | /// |
| 367 | /// Dropping `self` before the returned object is dropped will panic. |
| 368 | pub fn make_raw_fetcher(&mut self, channel: &'event_loop Channel) -> RawFetcher { |
| 369 | // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under |
| 370 | // the usual autocxx heuristics. |
| 371 | RawFetcher(unsafe { self.0.as_mut().MakeFetcher(channel) }.within_box()) |
| 372 | } |
| 373 | |
| 374 | // TODO(Brian): Expose timers and phased loops. Should we have `sleep`-style methods for those, |
| 375 | // instead of / in addition to mirroring C++ with separate setup and wait? |
| 376 | |
| 377 | // TODO(Brian): Expose OnRun. That should only be called once, so coalesce and have it return |
| 378 | // immediately afterwards. |
| 379 | } |
| 380 | |
| 381 | // SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL). |
| 382 | #[repr(transparent)] |
| 383 | pub struct RawWatcher(Pin<Box<ffi::aos::WatcherForRust>>); |
| 384 | |
| 385 | /// Provides async blocking access to messages on a channel. This will return every message on the |
| 386 | /// channel, in order. |
| 387 | /// |
| 388 | /// Use [`EventLoopRuntime::make_raw_watcher`] to create one of these. |
| 389 | /// |
| 390 | /// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs |
| 391 | /// for actually interpreting messages. You probably want a [`Watcher`] instead. |
| 392 | /// |
| 393 | /// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical |
| 394 | /// reasons. |
| 395 | /// |
| 396 | /// # Design |
| 397 | /// |
| 398 | /// We can't use [`futures::stream::Stream`] because our `Item` type is `Context<'_>`, which means |
| 399 | /// it's different for each `self` lifetime so we can't write a single type alias for it. We could |
| 400 | /// write an intermediate type with a generic lifetime that implements `Stream` and is returned |
| 401 | /// from a `make_stream` method, but that's what `Stream` is doing in the first place so adding |
| 402 | /// another level doesn't help anything. |
| 403 | /// |
| 404 | /// We also drop the extraneous `cx` argument that isn't used by this implementation anyways. |
| 405 | /// |
| 406 | /// We also run into some limitations in the borrow checker trying to implement `poll`, I think it's |
| 407 | /// the same one mentioned here: |
| 408 | /// 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 |
| 409 | /// We get around that one by moving the unbounded lifetime from the pointer dereference into the |
| 410 | /// function with the if statement. |
| 411 | impl RawWatcher { |
| 412 | /// Returns a Future to await the next value. This can be canceled (ie dropped) at will, |
| 413 | /// without skipping any messages. |
| 414 | /// |
| 415 | /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You |
| 416 | /// will need to call this function again to get the succeeding message. |
| 417 | /// |
| 418 | /// # Examples |
| 419 | /// |
| 420 | /// The common use case is immediately awaiting the next message: |
| 421 | /// ``` |
| 422 | /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::RawWatcher) { |
| 423 | /// println!("received: {:?}", watcher.next().await); |
| 424 | /// # } |
| 425 | /// ``` |
| 426 | /// |
| 427 | /// You can also await the first message from any of a set of channels: |
| 428 | /// ``` |
| 429 | /// # async fn select( |
| 430 | /// # mut watcher1: aos_events_event_loop_runtime::RawWatcher, |
| 431 | /// # mut watcher2: aos_events_event_loop_runtime::RawWatcher, |
| 432 | /// # ) { |
| 433 | /// futures::select! { |
| 434 | /// message1 = watcher1.next() => println!("channel 1: {:?}", message1), |
| 435 | /// message2 = watcher2.next() => println!("channel 2: {:?}", message2), |
| 436 | /// } |
| 437 | /// # } |
| 438 | /// ``` |
| 439 | /// |
| 440 | /// Note that due to the returned object borrowing the `self` reference, the borrow checker will |
| 441 | /// enforce only having a single of these returned objects at a time. Drop the previous message |
| 442 | /// before asking for the next one. That means this will not compile: |
| 443 | /// ```compile_fail |
| 444 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) { |
| 445 | /// let first = watcher.next(); |
| 446 | /// let second = watcher.next(); |
| 447 | /// first.await; |
| 448 | /// # } |
| 449 | /// ``` |
| 450 | /// and nor will this: |
| 451 | /// ```compile_fail |
| 452 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) { |
| 453 | /// let first = watcher.next().await; |
| 454 | /// watcher.next(); |
| 455 | /// println!("still have: {:?}", first); |
| 456 | /// # } |
| 457 | /// ``` |
| 458 | /// but this is fine: |
| 459 | /// ``` |
| 460 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) { |
| 461 | /// let first = watcher.next().await; |
| 462 | /// println!("have: {:?}", first); |
| 463 | /// watcher.next(); |
| 464 | /// # } |
| 465 | /// ``` |
| 466 | pub fn next(&mut self) -> RawWatcherNext { |
| 467 | RawWatcherNext(Some(self)) |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | /// The type returned from [`RawWatcher::next`], see there for details. |
| 472 | pub struct RawWatcherNext<'a>(Option<&'a mut RawWatcher>); |
| 473 | |
| 474 | impl<'a> Future for RawWatcherNext<'a> { |
| 475 | type Output = Context<'a>; |
| 476 | fn poll(mut self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<Context<'a>> { |
| 477 | let inner = self |
| 478 | .0 |
| 479 | .take() |
| 480 | .expect("May not call poll after it returns Ready"); |
| 481 | let maybe_context = inner.0.as_mut().PollNext(); |
| 482 | if maybe_context.is_null() { |
| 483 | // We're not returning a reference into it, so we can safely replace the reference to |
| 484 | // use again in the future. |
| 485 | self.0.replace(inner); |
| 486 | Poll::Pending |
| 487 | } else { |
| 488 | // SAFETY: We just checked if it's null. If not, it will be a valid pointer. It will |
| 489 | // remain a valid pointer for the borrow of the underlying `RawWatcher` (ie `'a`) |
| 490 | // because we're dropping `inner` (which is that reference), so it will need to be |
| 491 | // borrowed again which cannot happen before the end of `'a`. |
| 492 | Poll::Ready(Context(unsafe { &*maybe_context })) |
| 493 | } |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | impl FusedFuture for RawWatcherNext<'_> { |
| 498 | fn is_terminated(&self) -> bool { |
| 499 | self.0.is_none() |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | // SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL). |
| 504 | #[repr(transparent)] |
| 505 | pub struct RawFetcher(Pin<Box<ffi::aos::FetcherForRust>>); |
| 506 | |
| 507 | /// Provides access to messages on a channel, without the ability to wait for a new one. This |
| 508 | /// provides APIs to get the latest message at some time, and to follow along and retrieve each |
| 509 | /// message in order. |
| 510 | /// |
| 511 | /// Use [`EventLoopRuntime::make_raw_fetcher`] to create one of these. |
| 512 | /// |
| 513 | /// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs |
| 514 | /// for actually interpreting messages. You probably want a [`Fetcher`] instead. |
| 515 | impl RawFetcher { |
| 516 | pub fn fetch_next(&mut self) -> bool { |
| 517 | self.0.as_mut().FetchNext() |
| 518 | } |
| 519 | |
| 520 | pub fn fetch(&mut self) -> bool { |
| 521 | self.0.as_mut().Fetch() |
| 522 | } |
| 523 | |
| 524 | pub fn context(&self) -> Context { |
| 525 | Context(self.0.context()) |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | // SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL). |
| 530 | #[repr(transparent)] |
| 531 | pub struct RawSender(Pin<Box<ffi::aos::SenderForRust>>); |
| 532 | |
| 533 | /// Allows sending messages on a channel. |
| 534 | /// |
| 535 | /// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs |
| 536 | /// for actually creating messages to send. You probably want a [`Sender`] instead. |
| 537 | /// |
| 538 | /// Use [`EventLoopRuntime::make_raw_sender`] to create one of these. |
| 539 | impl RawSender { |
| 540 | fn buffer(&mut self) -> &mut [u8] { |
| 541 | // SAFETY: This is a valid slice, and `u8` doesn't have any alignment requirements. |
| 542 | unsafe { slice::from_raw_parts_mut(self.0.as_mut().data(), self.0.as_mut().size()) } |
| 543 | } |
| 544 | |
| 545 | /// Returns an object which can be used to build a message. |
| 546 | /// |
| 547 | /// # Examples |
| 548 | /// |
| 549 | /// ``` |
| 550 | /// # use pong_rust_fbs::aos::examples::PongBuilder; |
| 551 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) { |
| 552 | /// # unsafe { |
| 553 | /// let mut builder = sender.make_builder(); |
| 554 | /// let pong = PongBuilder::new(builder.fbb()).finish(); |
| 555 | /// builder.send(pong); |
| 556 | /// # } |
| 557 | /// # } |
| 558 | /// ``` |
| 559 | /// |
| 560 | /// You can bail out of building a message and build another one: |
| 561 | /// ``` |
| 562 | /// # use pong_rust_fbs::aos::examples::PongBuilder; |
| 563 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) { |
| 564 | /// # unsafe { |
| 565 | /// let mut builder1 = sender.make_builder(); |
| 566 | /// builder1.fbb(); |
| 567 | /// let mut builder2 = sender.make_builder(); |
| 568 | /// let pong = PongBuilder::new(builder2.fbb()).finish(); |
| 569 | /// builder2.send(pong); |
| 570 | /// # } |
| 571 | /// # } |
| 572 | /// ``` |
| 573 | /// but you cannot build two messages at the same time with a single builder: |
| 574 | /// ```compile_fail |
| 575 | /// # use pong_rust_fbs::aos::examples::PongBuilder; |
| 576 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) { |
| 577 | /// # unsafe { |
| 578 | /// let mut builder1 = sender.make_builder(); |
| 579 | /// let mut builder2 = sender.make_builder(); |
| 580 | /// PongBuilder::new(builder2.fbb()).finish(); |
| 581 | /// PongBuilder::new(builder1.fbb()).finish(); |
| 582 | /// # } |
| 583 | /// # } |
| 584 | /// ``` |
| 585 | pub fn make_builder(&mut self) -> RawBuilder { |
| 586 | // TODO(Brian): Actually use the provided buffer instead of just using its |
| 587 | // size to allocate a separate one. |
| 588 | // |
| 589 | // See https://github.com/google/flatbuffers/issues/7385. |
| 590 | let fbb = flatbuffers::FlatBufferBuilder::with_capacity(self.buffer().len()); |
| 591 | RawBuilder { |
| 592 | raw_sender: self, |
| 593 | fbb, |
| 594 | } |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | #[derive(Clone, Copy, Eq, PartialEq, Debug, Error)] |
| 599 | pub enum SendError { |
| 600 | #[error("messages have been sent too fast on this channel")] |
| 601 | MessagesSentTooFast, |
| 602 | #[error("invalid redzone data, shared memory corruption detected")] |
| 603 | InvalidRedzone, |
| 604 | } |
| 605 | |
| 606 | /// Used for building a message. See [`RawSender::make_builder`] for details. |
| 607 | pub struct RawBuilder<'sender> { |
| 608 | raw_sender: &'sender mut RawSender, |
| 609 | fbb: flatbuffers::FlatBufferBuilder<'sender>, |
| 610 | } |
| 611 | |
| 612 | impl<'sender> RawBuilder<'sender> { |
| 613 | pub fn fbb(&mut self) -> &mut flatbuffers::FlatBufferBuilder<'sender> { |
| 614 | &mut self.fbb |
| 615 | } |
| 616 | |
| 617 | /// # Safety |
| 618 | /// |
| 619 | /// `T` must match the type of the channel of the sender this builder was created from. |
| 620 | pub unsafe fn send<T>(mut self, root: flatbuffers::WIPOffset<T>) -> Result<(), SendError> { |
| 621 | self.fbb.finish_minimal(root); |
| 622 | let data = self.fbb.finished_data(); |
| 623 | |
| 624 | use ffi::aos::RawSender_Error as FfiError; |
| 625 | // SAFETY: This is a valid buffer we're passing. |
| 626 | match unsafe { |
| 627 | self.raw_sender |
| 628 | .0 |
| 629 | .as_mut() |
| 630 | .CopyAndSend(data.as_ptr(), data.len()) |
| 631 | } { |
| 632 | FfiError::kOk => Ok(()), |
| 633 | FfiError::kMessagesSentTooFast => Err(SendError::MessagesSentTooFast), |
| 634 | FfiError::kInvalidRedzone => Err(SendError::InvalidRedzone), |
| 635 | } |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | #[repr(transparent)] |
| 640 | #[derive(Clone, Copy)] |
| 641 | pub struct Context<'context>(&'context ffi::aos::Context); |
| 642 | |
| 643 | impl fmt::Debug for Context<'_> { |
| 644 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 645 | // TODO(Brian): Add the realtime timestamps here. |
| 646 | f.debug_struct("Context") |
| 647 | .field("monotonic_event_time", &self.monotonic_event_time()) |
| 648 | .field("monotonic_remote_time", &self.monotonic_remote_time()) |
| 649 | .field("queue_index", &self.queue_index()) |
| 650 | .field("remote_queue_index", &self.remote_queue_index()) |
| 651 | .field("size", &self.data().map(|data| data.len())) |
| 652 | .field("buffer_index", &self.buffer_index()) |
| 653 | .field("source_boot_uuid", &self.source_boot_uuid()) |
| 654 | .finish() |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | // TODO(Brian): Add the realtime timestamps here. |
| 659 | impl<'context> Context<'context> { |
| 660 | pub fn monotonic_event_time(self) -> MonotonicInstant { |
| 661 | MonotonicInstant(self.0.monotonic_event_time) |
| 662 | } |
| 663 | |
| 664 | pub fn monotonic_remote_time(self) -> MonotonicInstant { |
| 665 | MonotonicInstant(self.0.monotonic_remote_time) |
| 666 | } |
| 667 | |
| 668 | pub fn queue_index(self) -> u32 { |
| 669 | self.0.queue_index |
| 670 | } |
| 671 | pub fn remote_queue_index(self) -> u32 { |
| 672 | self.0.remote_queue_index |
| 673 | } |
| 674 | |
| 675 | pub fn data(self) -> Option<&'context [u8]> { |
| 676 | if self.0.data.is_null() { |
| 677 | None |
| 678 | } else { |
| 679 | // SAFETY: |
| 680 | // * `u8` has no alignment requirements |
| 681 | // * It must be a single initialized flatbuffers buffer |
| 682 | // * The borrow in `self.0` guarantees it won't be modified for `'context` |
| 683 | Some(unsafe { slice::from_raw_parts(self.0.data as *const u8, self.0.size) }) |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | pub fn buffer_index(self) -> i32 { |
| 688 | self.0.buffer_index |
| 689 | } |
| 690 | |
| 691 | pub fn source_boot_uuid(self) -> &'context Uuid { |
| 692 | // SAFETY: `self` has a valid C++ object. C++ guarantees that the return value will be |
| 693 | // valid until something changes the context, which is `'context`. |
| 694 | Uuid::from_bytes_ref(&self.0.source_boot_uuid) |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | /// Represents a `aos::monotonic_clock::time_point` in a natural Rust way. This |
| 699 | /// is intended to have the same API as [`std::time::Instant`], any missing |
| 700 | /// functionality can be added if useful. |
| 701 | /// |
| 702 | /// TODO(Brian): Do RealtimeInstant too. Use a macro? Integer as a generic |
| 703 | /// parameter to distinguish them? Or just copy/paste? |
| 704 | #[repr(transparent)] |
| 705 | #[derive(Clone, Copy, Eq, PartialEq)] |
| 706 | pub struct MonotonicInstant(i64); |
| 707 | |
| 708 | impl MonotonicInstant { |
| 709 | /// `aos::monotonic_clock::min_time`, commonly used as a sentinel value. |
| 710 | pub const MIN_TIME: Self = Self(i64::MIN); |
| 711 | |
| 712 | pub fn is_min_time(self) -> bool { |
| 713 | self == Self::MIN_TIME |
| 714 | } |
| 715 | |
| 716 | pub fn duration_since_epoch(self) -> Option<Duration> { |
| 717 | if self.is_min_time() { |
| 718 | None |
| 719 | } else { |
| 720 | Some(Duration::from_nanos(self.0.try_into().expect( |
| 721 | "monotonic_clock::time_point should always be after the epoch", |
| 722 | ))) |
| 723 | } |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | impl fmt::Debug for MonotonicInstant { |
| 728 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 729 | self.duration_since_epoch().fmt(f) |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | mod panic_waker { |
| 734 | use std::task::{RawWaker, RawWakerVTable, Waker}; |
| 735 | |
| 736 | unsafe fn clone_panic_waker(_data: *const ()) -> RawWaker { |
| 737 | raw_panic_waker() |
| 738 | } |
| 739 | |
| 740 | unsafe fn noop(_data: *const ()) {} |
| 741 | |
| 742 | unsafe fn wake_panic(_data: *const ()) { |
| 743 | panic!("Nothing should wake EventLoopRuntime's waker"); |
| 744 | } |
| 745 | |
| 746 | const PANIC_WAKER_VTABLE: RawWakerVTable = |
| 747 | RawWakerVTable::new(clone_panic_waker, wake_panic, wake_panic, noop); |
| 748 | |
| 749 | fn raw_panic_waker() -> RawWaker { |
| 750 | RawWaker::new(std::ptr::null(), &PANIC_WAKER_VTABLE) |
| 751 | } |
| 752 | |
| 753 | pub fn panic_waker() -> Waker { |
| 754 | // SAFETY: The implementations of the RawWakerVTable functions do what is required of them. |
| 755 | unsafe { Waker::from_raw(raw_panic_waker()) } |
| 756 | } |
| 757 | } |
| 758 | |
| 759 | use panic_waker::panic_waker; |