Skip to main content

astrs_node_api/output/
typed.rs

1//! [`Output<T>`] — the typed publishing handle of blueprint §9.1.
2//!
3//! ```no_run
4//! # use astrs_node_api::prelude::*;
5//! # use astrs_node_api::message::Vector3;
6//! # fn run(node: &mut Node) -> Result<(), NodeError> {
7//! let mut velocity = node.output::<Vector3>("velocity")?;
8//! velocity.send(Vector3::new(1.0, 0.0, 0.0), velocity.metadata())?;
9//! # Ok(())
10//! # }
11//! ```
12//!
13//! `Output<T>` is a thin typed skin over [`RawOutput`]: it encodes through
14//! `T`'s [`AstrsMessage`] implementation and hands the bytes to exactly the
15//! same send path, so a typed publish is neither slower nor differently
16//! routed than an untyped one.
17//!
18//! # `impl Into<T>`
19//!
20//! [`Output::send`] takes `impl Into<T>` rather than `T`, which is what lets
21//! a scalar channel read as `speed.send(2.5, meta)` even though the message
22//! type is [`Scalar<f64>`](crate::message::Scalar) — see that module for why
23//! the wrapper exists at all.
24//!
25//! # Type checking
26//!
27//! Opening a typed handle checks `T::URN` against the port's declared type
28//! under `ASTRS_TYPE_CHECK` (§9.2): `off` skips it, `warn` logs a mismatch and
29//! continues, `error` refuses the handle. The default is `warn` in 0.1.0 — a
30//! type system nobody can switch on is useless, and one that breaks every
31//! existing graph on upgrade is worse.
32
33use core::marker::PhantomData;
34
35use astrs_data::{ArrayRef, AstrsMessage, RecordBatch};
36use astrs_wire::{DataId, Metadata, PortRef};
37
38use crate::error::Result;
39use crate::output::{OutputSample, RawOutput};
40use crate::session::routes::RoutePlane;
41
42/// A typed publishing handle for one of the node's outputs.
43#[derive(Debug)]
44pub struct Output<T> {
45    /// The untyped handle everything funnels through.
46    raw: RawOutput,
47    /// The message type this handle publishes.
48    marker: PhantomData<fn(T)>,
49}
50
51impl<T> Output<T> {
52    /// Wraps an untyped handle.
53    #[must_use]
54    pub const fn new(raw: RawOutput) -> Self {
55        Self {
56            raw,
57            marker: PhantomData,
58        }
59    }
60
61    /// The output's id.
62    #[must_use]
63    pub const fn id(&self) -> &DataId {
64        self.raw.id()
65    }
66
67    /// The plane this output publishes on right now (§6.3).
68    #[must_use]
69    pub fn plane(&self) -> RoutePlane {
70        self.raw.plane()
71    }
72
73    /// The consumers the daemon reported at upgrade time.
74    #[must_use]
75    pub fn consumers(&self) -> &[PortRef] {
76        self.raw.consumers()
77    }
78
79    /// A fresh metadata block stamped with this node's clock (§4.3).
80    #[must_use]
81    pub fn metadata(&self) -> Metadata {
82        self.raw.metadata()
83    }
84
85    /// The untyped handle underneath, for a send this type cannot express.
86    #[must_use]
87    pub const fn raw(&self) -> &RawOutput {
88        &self.raw
89    }
90
91    /// The untyped handle underneath, mutably.
92    pub const fn raw_mut(&mut self) -> &mut RawOutput {
93        &mut self.raw
94    }
95
96    /// Unwraps the typed skin.
97    #[must_use]
98    pub fn into_raw(self) -> RawOutput {
99        self.raw
100    }
101
102    /// Publishes raw payload bytes, bypassing the type.
103    ///
104    /// # Errors
105    ///
106    /// As [`RawOutput::send_bytes`].
107    pub fn send_bytes(&mut self, bytes: impl AsRef<[u8]>, metadata: Metadata) -> Result<()> {
108        self.raw.send_bytes(bytes, metadata)
109    }
110
111    /// Publishes a record batch, bypassing the type.
112    ///
113    /// # Errors
114    ///
115    /// As [`RawOutput::send_batch`].
116    pub fn send_batch(&mut self, batch: &RecordBatch, metadata: Metadata) -> Result<()> {
117        self.raw.send_batch(batch, metadata)
118    }
119
120    /// Publishes a single column as a whole payload, bypassing the type.
121    ///
122    /// # Errors
123    ///
124    /// As [`RawOutput::send_array`].
125    pub fn send_array(&mut self, array: ArrayRef, metadata: Metadata) -> Result<()> {
126        self.raw.send_array(array, metadata)
127    }
128
129    /// Reserves `len` bytes to write into (§9.1).
130    ///
131    /// # Errors
132    ///
133    /// As [`RawOutput::allocate`].
134    pub fn allocate(&mut self, len: usize) -> Result<OutputSample<'_>> {
135        self.raw.allocate(len)
136    }
137
138    /// Tells the daemon this output will produce nothing further.
139    ///
140    /// # Errors
141    ///
142    /// As [`RawOutput::close`].
143    pub fn close(&mut self) -> Result<()> {
144        self.raw.close()
145    }
146}
147
148impl<T: AstrsMessage> Output<T> {
149    /// The type URN this handle publishes.
150    #[must_use]
151    pub const fn type_urn(&self) -> &'static str {
152        T::URN
153    }
154
155    /// Publishes one value.
156    ///
157    /// # Errors
158    ///
159    /// [`crate::NodeError::Data`] when the value cannot be encoded, plus
160    /// whatever [`RawOutput::send_batch`] reports.
161    pub fn send(&mut self, value: impl Into<T>, metadata: Metadata) -> Result<()> {
162        let batch = value.into().to_record_batch()?;
163        self.raw.send_batch(&batch, metadata)
164    }
165
166    /// Publishes one value with a freshly stamped metadata block.
167    ///
168    /// The shortest form, for a node with nothing to correlate.
169    ///
170    /// # Errors
171    ///
172    /// As [`Output::send`].
173    pub fn publish(&mut self, value: impl Into<T>) -> Result<()> {
174        let metadata = self.metadata();
175        self.send(value, metadata)
176    }
177
178    /// Publishes one value, following `cause`'s correlation and timing
179    /// metadata (§9.4).
180    ///
181    /// This is the blueprint §9.1 shape: `detections.send(run_model(&img)?,
182    /// meta.follow())?` — the response of a service, the next chunk of a
183    /// stream, and the derived output of a pipeline stage all keep the keys
184    /// that make them traceable.
185    ///
186    /// # Errors
187    ///
188    /// As [`Output::send`].
189    pub fn send_following(&mut self, value: impl Into<T>, cause: &Metadata) -> Result<()> {
190        self.send(value, cause.follow())
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
197
198    use super::*;
199    use crate::events::EventSource;
200    use crate::message::{Scalar, Vector3};
201    use crate::runtime::NodeRuntime;
202    use crate::session::{OUTGOING_CAPACITY, Outgoing, SessionShared};
203    use astrs_wire::{
204        DataflowId, FrameLimits, NodeId, NodeRequest, NodeSource, NodeSpawnSpec, SessionId,
205    };
206    use std::sync::Arc;
207    use tokio::sync::mpsc;
208
209    fn handle<T>() -> (Output<T>, Arc<SessionShared>, mpsc::Receiver<Outgoing>) {
210        let (sender, receiver) = mpsc::channel(OUTGOING_CAPACITY);
211        let spec = Arc::new(NodeSpawnSpec::new(
212            DataflowId::from_u128(1),
213            NodeId::new("planner").unwrap(),
214            0,
215            NodeSource::Dynamic,
216        ));
217        let shared = Arc::new(SessionShared::new(
218            spec,
219            SessionId::from_u128(1),
220            sender,
221            Arc::new(EventSource::new()),
222            NodeRuntime::acquire().unwrap(),
223            4096,
224            FrameLimits::uds(),
225        ));
226        let raw = RawOutput::new(Arc::clone(&shared), DataId::new("velocity").unwrap());
227        (Output::new(raw), shared, receiver)
228    }
229
230    fn take_payload(receiver: &mut mpsc::Receiver<Outgoing>) -> (Metadata, Vec<u8>) {
231        loop {
232            let Ok(Outgoing::Request(request)) = receiver.try_recv() else {
233                panic!("expected a request");
234            };
235            if let NodeRequest::SendMessage {
236                metadata, payload, ..
237            } = *request
238            {
239                return (metadata, payload.bytes().unwrap_or_default().to_vec());
240            }
241        }
242    }
243
244    #[test]
245    fn a_typed_send_round_trips_through_the_wire_payload() {
246        let (mut output, _shared, mut receiver) = handle::<Vector3>();
247        let value = Vector3::new(1.0, 2.0, 3.0);
248        output.send(value, output.metadata()).unwrap();
249
250        let (_, bytes) = take_payload(&mut receiver);
251        let batch = astrs_data::ipc::decode_payload(&bytes).unwrap();
252        assert_eq!(Vector3::from_record_batch(&batch).unwrap(), value);
253        assert_eq!(output.type_urn(), "std/geometry/v1/Vector3");
254        assert_eq!(output.id().as_str(), "velocity");
255    }
256
257    #[test]
258    fn into_makes_scalar_channels_read_naturally() {
259        let (mut output, _shared, mut receiver) = handle::<Scalar<f64>>();
260        output.publish(2.5_f64).unwrap();
261        let (_, bytes) = take_payload(&mut receiver);
262        let batch = astrs_data::ipc::decode_payload(&bytes).unwrap();
263        assert_eq!(
264            Scalar::<f64>::from_record_batch(&batch)
265                .unwrap()
266                .into_inner(),
267            2.5
268        );
269    }
270
271    #[test]
272    fn following_keeps_the_correlation_keys() {
273        let (mut output, _shared, mut receiver) = handle::<Vector3>();
274        let mut cause = output.metadata();
275        cause.set_request_id("req-7");
276        output.send_following(Vector3::default(), &cause).unwrap();
277        let (metadata, _) = take_payload(&mut receiver);
278        assert_eq!(metadata.request_id(), Some("req-7"));
279    }
280
281    #[test]
282    fn the_untyped_faces_are_reachable() {
283        let (mut output, _shared, mut receiver) = handle::<Vector3>();
284        output.send_bytes(vec![1, 2, 3], output.metadata()).unwrap();
285        let (_, bytes) = take_payload(&mut receiver);
286        assert_eq!(bytes, vec![1, 2, 3]);
287
288        assert_eq!(output.plane(), RoutePlane::Daemon);
289        assert!(output.consumers().is_empty());
290        assert_eq!(output.raw().id().as_str(), "velocity");
291        assert_eq!(output.raw_mut().id().as_str(), "velocity");
292
293        let mut sample = output.allocate(2).unwrap();
294        sample.as_mut_slice().copy_from_slice(&[8, 9]);
295        sample.send(Metadata::default()).unwrap();
296        let (_, bytes) = take_payload(&mut receiver);
297        assert_eq!(bytes, vec![8, 9]);
298
299        output.close().unwrap();
300        assert!(output.into_raw().is_closed());
301    }
302}