1use crate::active_plans::PlanRuntime;
5use crate::pb::executor::rtdl_event::RtdlEventEnum;
6use crate::pb::executor::{RtdlEvent, RtdlPlanComplete, RtdlPlanStarted};
7use crate::pb::pilot::rtdl_node_state::RtdlNodeStateEnum;
8use crate::pb::pilot::{CapabilityCallResult, Plan, RtdlNodeState};
9use tokio::sync::mpsc::Sender;
10use tonic::Status;
11
12const RTDL_SEQUENCE: u32 = 0;
13const RTDL_PARALLEL: u32 = 1;
14
15#[derive(Clone)]
17pub struct NodeEventContext {
18 pub plan_id: String,
20 pub node_index: u32,
22 pub node_kind: u32,
24 pub op_id: String,
26 pub description: String,
28}
29
30pub fn is_terminal_state(state: u32) -> bool {
32 matches!(
33 RtdlNodeStateEnum::try_from(state as i32),
34 Ok(RtdlNodeStateEnum::Succeeded
35 | RtdlNodeStateEnum::Failed
36 | RtdlNodeStateEnum::Canceled
37 | RtdlNodeStateEnum::Timeout)
38 )
39}
40
41pub fn plan_started(plan_id: String) -> RtdlEvent {
43 RtdlEvent {
44 event_kind: RtdlEventEnum::PlanStarted as u32,
45 plan_started: Some(RtdlPlanStarted { plan_id }),
46 ..Default::default()
47 }
48}
49
50pub fn node_state(
52 node: &NodeEventContext,
53 state: u32,
54 operator_detail: String,
55 leaf_result: Option<CapabilityCallResult>,
56) -> RtdlEvent {
57 RtdlEvent {
58 event_kind: RtdlEventEnum::NodeState as u32,
59 node_state: Some(RtdlNodeState {
60 plan_id: node.plan_id.clone(),
61 node_index: node.node_index,
62 node_kind: node.node_kind,
63 state,
64 operator_detail,
65 leaf_result,
66 op_id: node.op_id.clone(),
67 description: node.description.clone(),
68 }),
69 ..Default::default()
70 }
71}
72
73pub fn node_state_from_result(
74 node: &NodeEventContext,
75 result: CapabilityCallResult,
76 state: u32,
77) -> RtdlEvent {
78 node_state(node, state, String::new(), Some(result))
79}
80
81pub fn operator_node_state(node: &NodeEventContext, state: u32, detail: String) -> RtdlEvent {
82 node_state(node, state, detail, None)
83}
84
85pub fn plan_complete(plan_id: String, any_failed: bool) -> RtdlEvent {
87 RtdlEvent {
88 event_kind: RtdlEventEnum::PlanComplete as u32,
89 plan_complete: Some(RtdlPlanComplete {
90 plan_id,
91 any_failed,
92 }),
93 ..Default::default()
94 }
95}
96
97pub(crate) fn node_event_context(plan: &Plan, node_index: usize) -> NodeEventContext {
99 let node = &plan.nodes[node_index];
100 NodeEventContext {
101 plan_id: plan.plan_id.clone(),
102 node_index: node_index as u32,
103 node_kind: node.node_kind,
104 op_id: node.op_id.clone(),
105 description: node.description.clone(),
106 }
107}
108
109pub(crate) async fn send_operator_state(
111 tx: &Sender<Result<RtdlEvent, Status>>,
112 node: &NodeEventContext,
113 state: u32,
114 reason: &str,
115 runtime: &PlanRuntime,
116) {
117 let op = match node.node_kind {
118 RTDL_SEQUENCE => "sequence",
119 RTDL_PARALLEL => "parallel",
120 3 => "if",
121 4 => "repeat",
122 5 => "while",
123 _ => "operator",
124 };
125 let detail = format!(
126 "RTDL {op} op_id={} {reason}: {}",
127 node.op_id, node.description
128 );
129 runtime
130 .record_op_state(&node.plan_id, &node.op_id, state)
131 .await;
132 let _ = tx.send(Ok(operator_node_state(node, state, detail))).await;
133}
134
135pub(crate) async fn send_node_failure(
137 tx: &Sender<Result<RtdlEvent, Status>>,
138 node: &NodeEventContext,
139 detail: String,
140 runtime: &PlanRuntime,
141) {
142 robonix_scribe::warn!(
143 "[executor/rtdl] plan_id={} node={} op_id={} failed: {}",
144 node.plan_id,
145 node.node_index,
146 node.op_id,
147 detail
148 );
149 let state = RtdlNodeStateEnum::Failed as u32;
150 runtime
151 .record_op_state(&node.plan_id, &node.op_id, state)
152 .await;
153 let _ = tx.send(Ok(operator_node_state(node, state, detail))).await;
154}
155
156pub(crate) async fn send_operator_final(
158 tx: &Sender<Result<RtdlEvent, Status>>,
159 node: &NodeEventContext,
160 failed: bool,
161 cancelled: bool,
162 runtime: &PlanRuntime,
163) {
164 let (state, reason) = if cancelled {
165 (RtdlNodeStateEnum::Canceled as u32, "was canceled")
166 } else if failed {
167 (
168 RtdlNodeStateEnum::Failed as u32,
169 "failed because one or more child nodes failed",
170 )
171 } else {
172 (
173 RtdlNodeStateEnum::Succeeded as u32,
174 "completed successfully",
175 )
176 };
177 send_operator_state(tx, node, state, reason, runtime).await;
178}
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183
184 #[test]
186 fn node_state_uses_plan_and_node_fields() {
187 let event = node_state(
188 &NodeEventContext {
189 plan_id: "p".into(),
190 node_index: 7,
191 node_kind: 2,
192 op_id: "op_1".into(),
193 description: "take a camera snapshot".into(),
194 },
195 RtdlNodeStateEnum::Running as u32,
196 "operator detail".into(),
197 None,
198 );
199 let ns = event.node_state.unwrap();
200
201 assert_eq!(event.event_kind, RtdlEventEnum::NodeState as u32);
202 assert_eq!(ns.plan_id, "p");
203 assert_eq!(ns.node_index, 7);
204 assert_eq!(ns.node_kind, 2);
205 assert_eq!(ns.state, RtdlNodeStateEnum::Running as u32);
206 assert_eq!(ns.operator_detail, "operator detail");
207 assert!(ns.leaf_result.is_none());
208 assert_eq!(ns.op_id, "op_1");
209 assert_eq!(ns.description, "take a camera snapshot");
210 }
211
212 #[tokio::test]
214 async fn operator_terminal_event_carries_node_identity() {
215 let (tx, mut rx) = tokio::sync::mpsc::channel(1);
216 let node = NodeEventContext {
217 plan_id: "p".to_string(),
218 node_index: 0,
219 node_kind: RTDL_SEQUENCE,
220 op_id: "op_1".to_string(),
221 description: "run the ordered checks".to_string(),
222 };
223
224 let runtime = PlanRuntime::default();
225 send_operator_state(
226 &tx,
227 &node,
228 RtdlNodeStateEnum::Succeeded as u32,
229 "completed successfully",
230 &runtime,
231 )
232 .await;
233
234 let event = rx.recv().await.unwrap().unwrap();
235 let ns = event.node_state.unwrap();
236 assert_eq!(event.event_kind, RtdlEventEnum::NodeState as u32);
237 assert_eq!(ns.op_id, "op_1");
238 assert_eq!(ns.description, "run the ordered checks");
239 assert_eq!(ns.state, RtdlNodeStateEnum::Succeeded as u32);
240 assert!(ns.leaf_result.is_none());
241 assert!(ns.operator_detail.contains("RTDL sequence op_id=op_1"));
242 }
243}