Skip to main content

astrs_node_api/patterns/
action.rs

1//! Long-running goals with a status FSM (blueprint §9.4,
2//! `goal_id`/`goal_status`).
3//!
4//! ```text
5//!            ┌──────────► Canceling ──► Canceled
6//!            │                ▲
7//!   Accepted ┴──► Executing ──┼──► Succeeded
8//!                             └──► Aborted
9//! ```
10//!
11//! The states are [`astrs_wire::GoalStatus`], whose discriminants match ROS 2's
12//! `action_msgs/msg/GoalStatus` exactly, so `astrs-ros2` bridges an action in
13//! either direction without a translation table.
14//!
15//! # The FSM is enforced, not documented
16//!
17//! [`GoalTracker`] refuses an illegal transition — `Succeeded → Executing`, a
18//! status after a terminal one, a status for a goal it has never seen — with
19//! [`crate::NodeError::Pattern`]. A client that trusts a server's status
20//! sequence without checking it will eventually meet a server that resends,
21//! reorders, or reports a terminal status twice; the tracker turns each of
22//! those into an error at the moment it happens rather than a wrong decision
23//! ten seconds later.
24//!
25//! # Feedback
26//!
27//! A feedback message is a status update carrying [`GoalStatus::Executing`]
28//! and a payload. There is no separate feedback topic, because there does not
29//! need to be one: it is the same edge, the same `goal_id`, and the queue
30//! immunity that `goal_status` already confers (§11.2).
31
32use core::fmt;
33use std::collections::BTreeMap;
34
35use astrs_data::AstrsMessage;
36use astrs_wire::{DataId, GoalStatus, Metadata};
37
38use crate::error::{NodeError, Result};
39use crate::events::Event;
40use crate::node::Node;
41use crate::output::{Output, RawOutput};
42use crate::payload::Payload;
43
44/// One action goal's identity, stable for its whole lifetime (§9.4).
45#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub struct GoalId(String);
47
48impl GoalId {
49    /// A fresh id.
50    #[must_use]
51    pub fn generate() -> Self {
52        Self(super::fresh_id())
53    }
54
55    /// Wraps an existing id.
56    #[must_use]
57    pub fn new(id: impl Into<String>) -> Self {
58        Self(id.into())
59    }
60
61    /// The id as text.
62    #[must_use]
63    pub fn as_str(&self) -> &str {
64        &self.0
65    }
66
67    /// Unwraps the id.
68    #[must_use]
69    pub fn into_string(self) -> String {
70        self.0
71    }
72}
73
74impl fmt::Display for GoalId {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        f.write_str(&self.0)
77    }
78}
79
80impl From<String> for GoalId {
81    fn from(id: String) -> Self {
82        Self(id)
83    }
84}
85
86/// One status update, as a client or server sees it.
87#[derive(Debug)]
88pub struct ActionOutcome {
89    /// The input it arrived on.
90    pub input: DataId,
91    /// The goal it concerns.
92    pub goal: GoalId,
93    /// The status it reports.
94    pub status: GoalStatus,
95    /// Its metadata.
96    pub metadata: Metadata,
97    /// The payload — a result for a terminal status, feedback otherwise.
98    pub payload: Payload,
99}
100
101impl ActionOutcome {
102    /// Reads a status update out of an event, if it is one.
103    ///
104    /// An input with a `goal_id` but no `goal_status` is the *goal itself*
105    /// (what a server receives), not an update; it is returned unchanged so a
106    /// server can handle it with [`ActionOutcome::goal_of`].
107    pub fn from_event(event: Event) -> core::result::Result<Self, Box<Event>> {
108        let Event::Input { id, meta, data } = event else {
109            return Err(Box::new(event));
110        };
111        let (Some(goal), Some(status)) = (meta.goal_id().map(GoalId::new), meta.goal_status())
112        else {
113            return Err(Box::new(Event::Input { id, meta, data }));
114        };
115        Ok(Self {
116            input: id,
117            goal,
118            status,
119            metadata: meta,
120            payload: data,
121        })
122    }
123
124    /// The goal id of an event that carries one, whether or not it is a
125    /// status update.
126    #[must_use]
127    pub fn goal_of(event: &Event) -> Option<GoalId> {
128        event
129            .metadata()
130            .and_then(Metadata::goal_id)
131            .map(GoalId::new)
132    }
133
134    /// Whether this update ends the goal.
135    #[must_use]
136    pub fn is_terminal(&self) -> bool {
137        self.status.is_terminal()
138    }
139
140    /// Whether this update is feedback rather than an outcome.
141    #[must_use]
142    pub fn is_feedback(&self) -> bool {
143        self.status == GoalStatus::Executing && !self.payload.is_empty()
144    }
145
146    /// Decodes the payload.
147    ///
148    /// # Errors
149    ///
150    /// [`NodeError::Data`] when the payload is not a `T`.
151    pub fn view<T: crate::message::FromPayload>(&self) -> Result<T> {
152        self.payload.view()
153    }
154}
155
156/// A client-side view of every goal in flight, with the FSM enforced.
157#[derive(Debug, Default)]
158pub struct GoalTracker {
159    /// The last status seen for each goal.
160    states: BTreeMap<GoalId, GoalStatus>,
161}
162
163impl GoalTracker {
164    /// An empty tracker.
165    #[must_use]
166    pub fn new() -> Self {
167        Self::default()
168    }
169
170    /// Records a goal this node just sent, in [`GoalStatus::Accepted`].
171    pub fn track(&mut self, goal: GoalId) {
172        let _previous = self.states.insert(goal, GoalStatus::Accepted);
173    }
174
175    /// The status last seen for `goal`.
176    #[must_use]
177    pub fn status(&self, goal: &GoalId) -> Option<GoalStatus> {
178        self.states.get(goal).copied()
179    }
180
181    /// How many goals are still in flight.
182    #[must_use]
183    pub fn in_flight(&self) -> usize {
184        self.states
185            .values()
186            .filter(|status| !status.is_terminal())
187            .count()
188    }
189
190    /// Every goal being tracked.
191    #[must_use]
192    pub fn goals(&self) -> Vec<GoalId> {
193        self.states.keys().cloned().collect()
194    }
195
196    /// Applies a status update, checking the FSM (§9.4).
197    ///
198    /// # Errors
199    ///
200    /// [`NodeError::Pattern`] for a goal that was never tracked, a transition
201    /// the FSM does not allow, or any update after a terminal status.
202    pub fn observe(&mut self, outcome: &ActionOutcome) -> Result<GoalStatus> {
203        let Some(current) = self.states.get(&outcome.goal).copied() else {
204            return Err(NodeError::Pattern(format!(
205                "status `{}` for goal `{}`, which this node never sent",
206                outcome.status, outcome.goal
207            )));
208        };
209        if current.is_terminal() {
210            return Err(NodeError::Pattern(format!(
211                "goal `{}` already ended as `{current}`; it cannot now be `{}`",
212                outcome.goal, outcome.status
213            )));
214        }
215        if current == outcome.status {
216            // A repeated non-terminal status is a heartbeat, not a
217            // transition: feedback arrives as repeated `Executing`.
218            return Ok(current);
219        }
220        if !current.can_transition_to(outcome.status) {
221            return Err(NodeError::Pattern(format!(
222                "goal `{}` cannot go from `{current}` to `{}`",
223                outcome.goal, outcome.status
224            )));
225        }
226        let _previous = self.states.insert(outcome.goal.clone(), outcome.status);
227        Ok(outcome.status)
228    }
229
230    /// Forgets every goal that has ended.
231    ///
232    /// Returns how many were removed. A long-running client that never prunes
233    /// grows one entry per goal forever, which is the sort of leak that only
234    /// shows up after a week of uptime.
235    pub fn prune_terminal(&mut self) -> usize {
236        let before = self.states.len();
237        self.states.retain(|_, status| !status.is_terminal());
238        before - self.states.len()
239    }
240}
241
242impl Node {
243    /// Sends a typed goal, returning its id (§9.4).
244    ///
245    /// The goal carries `goal_status = Accepted`, which is the first state of
246    /// the FSM: a client that has sent a goal and heard nothing knows it is
247    /// accepted-and-not-yet-executing rather than in no state at all.
248    ///
249    /// # Errors
250    ///
251    /// As [`Output::send`].
252    pub fn goal<T: AstrsMessage>(
253        &self,
254        output: &mut Output<T>,
255        value: impl Into<T>,
256    ) -> Result<GoalId> {
257        let goal = GoalId::generate();
258        let mut metadata = self.metadata();
259        metadata.set_goal_id(goal.as_str());
260        metadata.set_goal_status(GoalStatus::Accepted);
261        output.send(value, metadata)?;
262        Ok(goal)
263    }
264
265    /// Sends an untyped goal, returning its id.
266    ///
267    /// # Errors
268    ///
269    /// As [`RawOutput::send_bytes`].
270    pub fn goal_bytes(&self, output: &mut RawOutput, payload: impl AsRef<[u8]>) -> Result<GoalId> {
271        let goal = GoalId::generate();
272        let mut metadata = self.metadata();
273        metadata.set_goal_id(goal.as_str());
274        metadata.set_goal_status(GoalStatus::Accepted);
275        output.send_bytes(payload, metadata)?;
276        Ok(goal)
277    }
278
279    /// Reports a typed status update for `goal` (§9.4).
280    ///
281    /// # Errors
282    ///
283    /// As [`Output::send`].
284    pub fn goal_status<T: AstrsMessage>(
285        &self,
286        output: &mut Output<T>,
287        goal: &GoalId,
288        status: GoalStatus,
289        value: impl Into<T>,
290    ) -> Result<()> {
291        output.send(value, self.goal_metadata(goal, status))
292    }
293
294    /// Reports an untyped status update for `goal`.
295    ///
296    /// # Errors
297    ///
298    /// As [`RawOutput::send_bytes`].
299    pub fn goal_status_bytes(
300        &self,
301        output: &mut RawOutput,
302        goal: &GoalId,
303        status: GoalStatus,
304        payload: impl AsRef<[u8]>,
305    ) -> Result<()> {
306        output.send_bytes(payload, self.goal_metadata(goal, status))
307    }
308
309    /// Reports a status update with no payload — the common case for
310    /// `Accepted`, `Canceling` and a bare `Aborted`.
311    ///
312    /// # Errors
313    ///
314    /// As [`RawOutput::send_bytes`].
315    pub fn goal_signal(
316        &self,
317        output: &mut RawOutput,
318        goal: &GoalId,
319        status: GoalStatus,
320    ) -> Result<()> {
321        let batch = crate::message::Empty.to_record_batch()?;
322        output.send_batch(&batch, self.goal_metadata(goal, status))
323    }
324
325    /// The metadata a status update for `goal` carries.
326    #[must_use]
327    pub fn goal_metadata(&self, goal: &GoalId, status: GoalStatus) -> Metadata {
328        let mut metadata = self.metadata();
329        metadata.set_goal_id(goal.as_str());
330        metadata.set_goal_status(status);
331        metadata
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
338
339    use super::*;
340    use crate::message::Scalar;
341    use crate::testing::TestHarness;
342    use astrs_time::HlcTimestamp;
343    use std::time::Duration;
344
345    fn outcome(goal: &GoalId, status: GoalStatus) -> ActionOutcome {
346        let mut metadata = Metadata::new(HlcTimestamp::new(1, 0));
347        metadata.set_goal_id(goal.as_str());
348        metadata.set_goal_status(status);
349        ActionOutcome {
350            input: DataId::new("status").unwrap(),
351            goal: goal.clone(),
352            status,
353            metadata,
354            payload: Payload::empty(),
355        }
356    }
357
358    #[test]
359    fn goal_ids_are_fresh_and_printable() {
360        let goal = GoalId::generate();
361        assert_ne!(goal, GoalId::generate());
362        assert_eq!(goal.to_string(), goal.as_str());
363        assert_eq!(GoalId::new("g").into_string(), "g");
364        assert_eq!(GoalId::from("g".to_owned()).as_str(), "g");
365    }
366
367    #[test]
368    fn the_happy_path_is_accepted_executing_succeeded() {
369        let goal = GoalId::generate();
370        let mut tracker = GoalTracker::new();
371        tracker.track(goal.clone());
372        assert_eq!(tracker.status(&goal), Some(GoalStatus::Accepted));
373        assert_eq!(tracker.in_flight(), 1);
374        assert_eq!(tracker.goals(), vec![goal.clone()]);
375
376        assert_eq!(
377            tracker
378                .observe(&outcome(&goal, GoalStatus::Executing))
379                .unwrap(),
380            GoalStatus::Executing
381        );
382        assert_eq!(
383            tracker
384                .observe(&outcome(&goal, GoalStatus::Succeeded))
385                .unwrap(),
386            GoalStatus::Succeeded
387        );
388        assert_eq!(tracker.in_flight(), 0);
389        assert_eq!(tracker.prune_terminal(), 1);
390        assert!(tracker.goals().is_empty());
391    }
392
393    #[test]
394    fn a_repeated_executing_is_feedback_not_a_transition() {
395        let goal = GoalId::generate();
396        let mut tracker = GoalTracker::new();
397        tracker.track(goal.clone());
398        let _ = tracker
399            .observe(&outcome(&goal, GoalStatus::Executing))
400            .unwrap();
401        assert_eq!(
402            tracker
403                .observe(&outcome(&goal, GoalStatus::Executing))
404                .unwrap(),
405            GoalStatus::Executing
406        );
407    }
408
409    #[test]
410    fn an_illegal_transition_is_refused() {
411        let goal = GoalId::generate();
412        let mut tracker = GoalTracker::new();
413        tracker.track(goal.clone());
414        let _ = tracker
415            .observe(&outcome(&goal, GoalStatus::Succeeded))
416            .unwrap();
417        let error = tracker
418            .observe(&outcome(&goal, GoalStatus::Executing))
419            .unwrap_err();
420        assert!(matches!(error, NodeError::Pattern(_)), "{error}");
421        assert!(error.to_string().contains("already ended"), "{error}");
422    }
423
424    #[test]
425    fn a_status_for_an_unknown_goal_is_refused() {
426        let mut tracker = GoalTracker::new();
427        let error = tracker
428            .observe(&outcome(&GoalId::generate(), GoalStatus::Executing))
429            .unwrap_err();
430        assert!(error.to_string().contains("never sent"), "{error}");
431    }
432
433    #[test]
434    fn a_status_update_is_recognised_and_a_bare_goal_is_not() {
435        let goal = GoalId::generate();
436        let update = ActionOutcome::from_event(Event::Input {
437            id: DataId::new("status").unwrap(),
438            meta: {
439                let mut meta = Metadata::new(HlcTimestamp::new(1, 0));
440                meta.set_goal_id(goal.as_str());
441                meta.set_goal_status(GoalStatus::Executing);
442                meta
443            },
444            data: Payload::empty(),
445        })
446        .expect("a status update");
447        assert_eq!(update.goal, goal);
448        assert!(!update.is_terminal());
449        assert!(!update.is_feedback(), "an empty payload is not feedback");
450
451        // A goal *request* carries `goal_id` but no `goal_status`.
452        let mut meta = Metadata::new(HlcTimestamp::new(1, 0));
453        meta.set_goal_id(goal.as_str());
454        let event = Event::Input {
455            id: DataId::new("goal").unwrap(),
456            meta,
457            data: Payload::empty(),
458        };
459        let back = ActionOutcome::from_event(event).unwrap_err();
460        assert_eq!(ActionOutcome::goal_of(&back), Some(goal));
461        assert_eq!(ActionOutcome::goal_of(&Event::AllInputsClosed), None);
462    }
463
464    #[test]
465    fn a_full_action_between_two_nodes() {
466        let daemon = crate::testing::MockDaemon::start().unwrap();
467        let client_spec = astrs_wire::NodeSpawnSpec::new(
468            daemon.dataflow(),
469            astrs_wire::NodeId::new("client").unwrap(),
470            0,
471            astrs_wire::NodeSource::Dynamic,
472        )
473        .with_output(astrs_wire::OutputSpec::new(DataId::new("goal").unwrap()))
474        .with_input(astrs_wire::InputSpec::new(
475            DataId::new("status").unwrap(),
476            astrs_wire::PortRef::from_parts("server", "status").unwrap(),
477        ));
478        let server_spec = astrs_wire::NodeSpawnSpec::new(
479            daemon.dataflow(),
480            astrs_wire::NodeId::new("server").unwrap(),
481            0,
482            astrs_wire::NodeSource::Dynamic,
483        )
484        .with_input(astrs_wire::InputSpec::new(
485            DataId::new("goal").unwrap(),
486            astrs_wire::PortRef::from_parts("client", "goal").unwrap(),
487        ))
488        .with_output(astrs_wire::OutputSpec::new(DataId::new("status").unwrap()));
489
490        let (mut client, mut client_events) = daemon.connect_node(client_spec).unwrap();
491        let (mut server, mut server_events) = daemon.connect_node(server_spec).unwrap();
492
493        let mut goal_out = client.output::<Scalar<f64>>("goal").unwrap();
494        let goal = client.goal(&mut goal_out, 3.0_f64).unwrap();
495        let mut tracker = GoalTracker::new();
496        tracker.track(goal.clone());
497
498        // The server sees the goal and drives it to completion.
499        let event = server_events
500            .recv_timeout(Duration::from_secs(5))
501            .unwrap()
502            .expect("the goal");
503        let received = ActionOutcome::goal_of(&event).expect("a goal id");
504        assert_eq!(received, goal);
505
506        let mut status_out = server.output::<Scalar<f64>>("status").unwrap();
507        server
508            .goal_status(&mut status_out, &goal, GoalStatus::Executing, 0.5_f64)
509            .unwrap();
510        server
511            .goal_status(&mut status_out, &goal, GoalStatus::Succeeded, 1.0_f64)
512            .unwrap();
513
514        // The client walks the FSM.
515        let mut seen = Vec::new();
516        while seen.len() < 2 {
517            let event = client_events
518                .recv_timeout(Duration::from_secs(5))
519                .unwrap()
520                .expect("a status update");
521            let Ok(update) = ActionOutcome::from_event(event) else {
522                continue;
523            };
524            seen.push(tracker.observe(&update).unwrap());
525            if update.status == GoalStatus::Executing {
526                assert!(update.is_feedback(), "the payload makes it feedback");
527                assert_eq!(update.view::<Scalar<f64>>().unwrap().into_inner(), 0.5);
528            }
529        }
530        assert_eq!(seen, vec![GoalStatus::Executing, GoalStatus::Succeeded]);
531        assert_eq!(tracker.in_flight(), 0);
532    }
533
534    #[test]
535    fn a_bare_status_signal_carries_no_payload() {
536        let mut harness = TestHarness::start().unwrap();
537        let mut output = harness
538            .node
539            .raw_output(TestHarness::DEFAULT_OUTPUT)
540            .unwrap();
541        let goal = harness.node.goal_bytes(&mut output, vec![1]).unwrap();
542        harness
543            .node
544            .goal_signal(&mut output, &goal, GoalStatus::Canceling)
545            .unwrap();
546
547        let sends = harness
548            .daemon
549            .wait_for_sends(
550                harness.node.id(),
551                &DataId::new(TestHarness::DEFAULT_OUTPUT).unwrap(),
552                2,
553                Duration::from_secs(5),
554            )
555            .unwrap();
556        assert_eq!(sends[0].metadata.goal_status(), Some(GoalStatus::Accepted));
557        assert_eq!(sends[1].metadata.goal_status(), Some(GoalStatus::Canceling));
558        assert_eq!(sends[1].metadata.goal_id(), Some(goal.as_str()));
559    }
560}