1use 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub struct GoalId(String);
47
48impl GoalId {
49 #[must_use]
51 pub fn generate() -> Self {
52 Self(super::fresh_id())
53 }
54
55 #[must_use]
57 pub fn new(id: impl Into<String>) -> Self {
58 Self(id.into())
59 }
60
61 #[must_use]
63 pub fn as_str(&self) -> &str {
64 &self.0
65 }
66
67 #[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#[derive(Debug)]
88pub struct ActionOutcome {
89 pub input: DataId,
91 pub goal: GoalId,
93 pub status: GoalStatus,
95 pub metadata: Metadata,
97 pub payload: Payload,
99}
100
101impl ActionOutcome {
102 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 #[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 #[must_use]
136 pub fn is_terminal(&self) -> bool {
137 self.status.is_terminal()
138 }
139
140 #[must_use]
142 pub fn is_feedback(&self) -> bool {
143 self.status == GoalStatus::Executing && !self.payload.is_empty()
144 }
145
146 pub fn view<T: crate::message::FromPayload>(&self) -> Result<T> {
152 self.payload.view()
153 }
154}
155
156#[derive(Debug, Default)]
158pub struct GoalTracker {
159 states: BTreeMap<GoalId, GoalStatus>,
161}
162
163impl GoalTracker {
164 #[must_use]
166 pub fn new() -> Self {
167 Self::default()
168 }
169
170 pub fn track(&mut self, goal: GoalId) {
172 let _previous = self.states.insert(goal, GoalStatus::Accepted);
173 }
174
175 #[must_use]
177 pub fn status(&self, goal: &GoalId) -> Option<GoalStatus> {
178 self.states.get(goal).copied()
179 }
180
181 #[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 #[must_use]
192 pub fn goals(&self) -> Vec<GoalId> {
193 self.states.keys().cloned().collect()
194 }
195
196 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 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 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 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 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 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 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 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 #[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 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 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 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}