astrs_node_api/message/mod.rs
1//! The `std` URN message types (blueprint §9.2, §24.3).
2//!
3//! [`AstrsMessage`] itself lives in `astrs-data` — it has to, since
4//! `astrs-idl`'s ROS 2 codegen and `astrs-operator-macros`' derive both
5//! implement it and neither may depend upward on the node API (§4.1). This
6//! module is where the **hand-written implementations** live: one Rust type
7//! per entry of the §24.3 registry, each producing exactly the normative
8//! columnar layout that entry declares.
9//!
10//! ```text
11//! scalar bool · i8..i64 · u8..u64 · f32/f64 · String · Bytes · Empty · Timestamp
12//! geometry Vector3 · Quaternion · Pose · Transform · Twist · Accel
13//! sensor LaserScan · Imu · NavSatFix · Range · PointCloud
14//! vision Detections · Keypoints · Mask
15//! nav Odometry · Path · OccupancyGrid
16//! media Image · AudioFrame · CompressedImage
17//! ```
18//!
19//! # Two traits, on purpose
20//!
21//! | Trait | Direction | Why separate |
22//! |---|---|---|
23//! | [`FromPayload`] | payload → value | Some types can only be *read* — [`astrs_data::tensor::ImageView`] is a checked view over somebody else's columns, with no way to construct one from scratch |
24//! | [`AstrsMessage`] | both | Everything a node can also *send* |
25//!
26//! There is deliberately **no** blanket `impl<T: AstrsMessage> FromPayload for
27//! T`: the pair is written together for each type, which keeps a read-only
28//! implementation such as `ImageView`'s legal instead of overlapping with a
29//! blanket one. [`crate::Payload::view`] is generic over [`FromPayload`], so
30//! the blueprint's `let img: ImageView = data.view()?;` resolves.
31//!
32//! # The layouts are normative, not incidental
33//!
34//! Every implementation here is checked against
35//! [`astrs_data::TypeRegistry::std()`] by [`assert_registry_layout`] in its
36//! own test. Round-tripping an encoder against its own decoder proves nothing
37//! about §24.3 conformance; comparing the produced [`DataType`] against the
38//! registry's does.
39//!
40//! # Parameterised types
41//!
42//! `Image[pixel=…]`, `AudioFrame[sample=…]` and `PointCloud[fields=…]` have a
43//! layout that *depends* on a URN parameter, which a `const URN: &'static str`
44//! cannot express. Those three carry the parameter as a Rust value instead
45//! ([`PixelFormat`], [`SampleFormat`], [`PointCloud::field_names`]) and expose
46//! `to_record_batch`/`from_record_batch` as inherent methods with the same
47//! shape as the trait's, plus a `urn()` that renders the parameterised URN a
48//! port should declare. `CompressedImage`'s layout does *not* vary with its
49//! `format`, so it implements the trait proper.
50//!
51//! # Examples
52//!
53//! ```
54//! use astrs_node_api::message::{AstrsMessage, Pose, Vector3};
55//!
56//! let batch = Vector3::new(1.0, 2.0, 3.0).to_record_batch()?;
57//! assert_eq!(batch.num_rows(), 1);
58//! assert_eq!(Vector3::from_record_batch(&batch)?.y, 2.0);
59//! assert_eq!(Pose::URN, "std/geometry/v1/Pose");
60//! # Ok::<(), astrs_data::DataError>(())
61//! ```
62
63pub mod build;
64pub mod geometry;
65pub mod media;
66pub mod nav;
67pub mod read;
68pub mod scalar;
69pub mod sensor;
70pub mod vision;
71
72use astrs_data::urn::layout_of_str;
73use astrs_data::{ArrayRef, DataError, DataType, RecordBatch, Result};
74
75pub use astrs_data::AstrsMessage;
76pub use geometry::{Accel, Pose, Quaternion, Transform, Twist, Vector3};
77pub use media::{AudioFrame, CompressedImage, Image, ImageSamples, PixelFormat, SampleFormat};
78pub use nav::{OccupancyGrid, Odometry, Path, StampedPose};
79pub use scalar::{
80 Bytes, BytesRun, Duration, Empty, Flag, FlagRun, Scalar, ScalarRun, ScalarType, Text, TextRun,
81 Timestamp, TimestampRun,
82};
83pub use sensor::{Imu, LaserScan, NavSatFix, PointCloud, Range};
84pub use vision::{BoundingBox, Detections, Keypoint, Keypoints, Mask};
85
86/// Reading a typed value out of a decoded payload.
87///
88/// Implemented by every [`AstrsMessage`] in this module, and separately by the
89/// read-only view types that cannot be constructed from scratch.
90pub trait FromPayload: Sized {
91 /// Reads the value from a decoded payload batch.
92 ///
93 /// # Errors
94 ///
95 /// [`DataError`] when the batch's layout is not the one this type
96 /// expects, or when it holds no rows.
97 fn from_batch(batch: &RecordBatch) -> Result<Self>;
98}
99
100/// The single top-level payload column of `batch` (§6.1).
101///
102/// # Errors
103///
104/// [`DataError::ColumnCountMismatch`] when the batch carries no column.
105///
106/// # Examples
107///
108/// ```
109/// use astrs_data::prelude::*;
110/// use astrs_node_api::message::payload_column;
111///
112/// let batch = RecordBatch::from_payload(Float64Array::from_values([1.0]).into_array_ref());
113/// assert_eq!(payload_column(&batch)?.len(), 1);
114/// # Ok::<(), astrs_data::DataError>(())
115/// ```
116pub fn payload_column(batch: &RecordBatch) -> Result<&ArrayRef> {
117 batch
118 .payload_column()
119 .or_else(|| batch.column(0))
120 .ok_or(DataError::ColumnCountMismatch {
121 fields: 1,
122 columns: 0,
123 })
124}
125
126/// The single payload column of a batch that must hold exactly one row.
127///
128/// # Errors
129///
130/// [`DataError::MessageRowCount`] when the batch does not hold exactly one
131/// row, or whatever [`payload_column`] reports.
132pub fn single_row_column(batch: &RecordBatch) -> Result<&ArrayRef> {
133 if batch.num_rows() != 1 {
134 return Err(DataError::MessageRowCount {
135 actual: batch.num_rows(),
136 });
137 }
138 payload_column(batch)
139}
140
141/// Checks a type's layout against the `std` registry (§24.3).
142///
143/// This is the conformance gate every implementation in this module runs in
144/// its own test: it is the only check that can catch "my encoder and my
145/// decoder agree with each other, and both disagree with the spec".
146///
147/// # Errors
148///
149/// [`DataError::TypeUrn`] when the URN is unknown or its parameters do not
150/// validate, and [`DataError::TypeMismatch`] when the registry's layout is
151/// not the one the type produces.
152///
153/// # Examples
154///
155/// ```
156/// use astrs_node_api::message::{Pose, assert_registry_layout};
157///
158/// assert_registry_layout::<Pose>()?;
159/// # Ok::<(), astrs_data::DataError>(())
160/// ```
161pub fn assert_registry_layout<T: AstrsMessage>() -> Result<()> {
162 assert_layout_matches(T::URN, &T::data_type())
163}
164
165/// [`assert_registry_layout`] for a type whose registry entry requires a
166/// parameter the `const URN` cannot carry.
167///
168/// # Errors
169///
170/// As [`assert_registry_layout`].
171///
172/// # Examples
173///
174/// ```
175/// use astrs_node_api::message::{CompressedImage, assert_registry_layout_for};
176///
177/// assert_registry_layout_for::<CompressedImage>("std/media/v1/CompressedImage[format=jpeg]")?;
178/// # Ok::<(), astrs_data::DataError>(())
179/// ```
180pub fn assert_registry_layout_for<T: AstrsMessage>(urn: &str) -> Result<()> {
181 assert_layout_matches(urn, &T::data_type())
182}
183
184/// Compares a layout against the registry's entry for `urn`.
185///
186/// # Errors
187///
188/// As [`assert_registry_layout`].
189pub fn assert_layout_matches(urn: &str, actual: &DataType) -> Result<()> {
190 let expected = layout_of_str(urn)?;
191 if &expected == actual {
192 return Ok(());
193 }
194 Err(DataError::type_mismatch(expected, actual.clone()))
195}
196
197/// Writes the [`FromPayload`] half of an implementation, reading row zero.
198///
199/// Every implementation in this module pairs with one, since there is no
200/// blanket impl (see the module documentation).
201macro_rules! impl_from_payload {
202 ($ty:ty) => {
203 impl $crate::message::FromPayload for $ty {
204 fn from_batch(batch: &::astrs_data::RecordBatch) -> ::astrs_data::Result<Self> {
205 <Self as ::astrs_data::AstrsMessage>::from_record_batch(batch)
206 }
207 }
208 };
209}
210
211pub(crate) use impl_from_payload;
212
213#[cfg(test)]
214mod tests {
215 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
216
217 use super::*;
218 use astrs_data::array::{Float64Array, IntoArrayRef};
219
220 #[test]
221 fn the_payload_column_is_found_by_name_and_by_position() {
222 let batch = RecordBatch::from_payload(Float64Array::from_values([1.0]).into_array_ref());
223 assert_eq!(payload_column(&batch).unwrap().len(), 1);
224 assert_eq!(single_row_column(&batch).unwrap().len(), 1);
225 }
226
227 #[test]
228 fn a_batch_without_columns_is_reported() {
229 let batch =
230 RecordBatch::try_new_empty(std::sync::Arc::new(astrs_data::Schema::new(Vec::new())))
231 .unwrap();
232 assert!(matches!(
233 payload_column(&batch),
234 Err(DataError::ColumnCountMismatch { .. })
235 ));
236 }
237
238 #[test]
239 fn a_multi_row_batch_is_refused_where_one_row_is_required() {
240 let batch =
241 RecordBatch::from_payload(Float64Array::from_values([1.0, 2.0]).into_array_ref());
242 assert!(matches!(
243 single_row_column(&batch),
244 Err(DataError::MessageRowCount { actual: 2 })
245 ));
246 }
247
248 #[test]
249 fn conformance_reports_a_layout_that_drifted() {
250 assert!(assert_registry_layout::<Vector3>().is_ok());
251 let error =
252 assert_layout_matches("std/geometry/v1/Vector3", &DataType::Float64).unwrap_err();
253 assert!(matches!(error, DataError::TypeMismatch { .. }), "{error}");
254 }
255
256 #[test]
257 fn an_unknown_urn_is_reported_by_the_registry() {
258 let error = assert_layout_matches("std/core/v1/Nonexistent", &DataType::Null).unwrap_err();
259 assert!(!error.to_string().is_empty());
260 }
261
262 #[test]
263 fn schemas_carry_the_data_column() {
264 let schema = Vector3::schema();
265 assert_eq!(schema.fields().len(), 1);
266 assert_eq!(schema.field(0).map(astrs_data::Field::name), Some("data"));
267 assert_eq!(
268 schema.field(0).map(|field| field.data_type().clone()),
269 Some(Vector3::data_type())
270 );
271 }
272}