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