1use crate::pb::pilot::rtdl_node_state::RtdlNodeStateEnum;
5use crate::pb::pilot::{CapabilityCall, CapabilityCallResult, Plan, RtdlNode};
6use robonix_atlas::client::channel::Channel;
7use robonix_scribe::warn;
8use serde::Deserialize;
9use std::collections::HashMap;
10use std::sync::Arc;
11use std::time::Duration;
12use tokio::sync::Mutex;
13
14const DEFAULT_CANCEL_WAIT_MS: u64 = 5_000;
15
16#[derive(Clone, Default)]
18pub struct PlanRuntime {
19 inner: Arc<Mutex<HashMap<String, PlanRun>>>,
21 admission_closed: tokio::sync::watch::Sender<bool>,
23 changed: Arc<tokio::sync::Notify>,
25}
26
27#[derive(Clone)]
29pub struct RunningAsyncCall {
30 pub call_id: String,
32 pub channel: Channel,
34}
35
36struct PlanRun {
38 context: crate::execution_context::ExecutionContext,
39 cancelled: bool,
41 running_async: HashMap<String, RunningAsyncCall>,
43 description: String,
46 ops: Vec<OpMeta>,
49 op_state: HashMap<String, u32>,
52}
53
54#[derive(Clone)]
56struct OpMeta {
57 op_id: String,
59 description: String,
61 node_kind: u32,
63 provider_id: String,
65 contract_id: String,
67}
68
69impl From<&RtdlNode> for OpMeta {
70 fn from(node: &RtdlNode) -> Self {
71 Self {
72 op_id: node.op_id.clone(),
73 description: node.description.clone(),
74 node_kind: node.node_kind,
75 provider_id: node
76 .call
77 .as_ref()
78 .map(|call| call.provider_id.clone())
79 .unwrap_or_default(),
80 contract_id: node
81 .call
82 .as_ref()
83 .map(|call| call.contract_id.clone())
84 .unwrap_or_default(),
85 }
86 }
87}
88
89struct CancelSnapshot {
91 async_calls: Vec<RunningAsyncCall>,
93}
94
95struct CancelAllSnapshot {
97 async_calls: Vec<RunningAsyncCall>,
99 plan_ids: Vec<String>,
101}
102
103#[derive(Deserialize)]
105struct CancelPlanArgs {
106 plan_id: String,
108 wait_ms: Option<u64>,
110}
111
112impl PlanRuntime {
113 pub async fn close_admission(&self) -> Result<(), String> {
115 let plans = self.inner.lock().await;
116 if !plans.is_empty() {
117 return Err(
118 "Executor has active plans; use ControlPlan to cancel and wait, then retry".into(),
119 );
120 }
121 self.admission_closed.send_replace(true);
122 Ok(())
123 }
124
125 pub async fn open_admission(&self) {
126 let _plans = self.inner.lock().await;
127 self.admission_closed.send_replace(false);
128 }
129
130 pub fn subscribe_admission(&self) -> tokio::sync::watch::Receiver<bool> {
131 self.admission_closed.subscribe()
132 }
133
134 pub fn is_accepting_plans(&self) -> bool {
135 !*self.admission_closed.borrow()
136 }
137
138 pub async fn register_plan(&self, plan_id: &str) -> Result<(), String> {
140 let mut plans = self.inner.lock().await;
141 if !self.is_accepting_plans() {
142 return Err("Executor is not accepting plans; activate it before executing".into());
143 }
144 if plans.contains_key(plan_id) {
145 return Err(format!("plan {plan_id} is already active"));
146 }
147 plans.insert(
148 plan_id.into(),
149 PlanRun {
150 context: Default::default(),
151 cancelled: false,
152 running_async: HashMap::new(),
153 description: String::new(),
154 ops: Vec::new(),
155 op_state: HashMap::new(),
156 },
157 );
158 Ok(())
159 }
160
161 pub async fn record_stream_node(&self, plan_id: &str, node: &RtdlNode) -> bool {
163 let mut plans = self.inner.lock().await;
164 let Some(run) = plans.get_mut(plan_id) else {
165 return false;
166 };
167 if run.cancelled {
168 return false;
169 }
170 if run.ops.is_empty() {
171 run.description = node.description.clone();
172 }
173 run.ops.push(OpMeta::from(node));
174 true
175 }
176
177 pub async fn record_plan_ops(&self, plan: &Plan) {
181 let ops: Vec<OpMeta> = plan.nodes.iter().map(OpMeta::from).collect();
182 let description = plan
183 .nodes
184 .get(plan.root_index as usize)
185 .map(|n| n.description.clone())
186 .unwrap_or_default();
187 if let Some(run) = self.inner.lock().await.get_mut(&plan.plan_id) {
188 run.ops = ops;
189 run.description = description;
190 }
191 }
192
193 pub async fn context(&self, plan_id: &str) -> crate::execution_context::ExecutionContext {
194 self.inner
195 .lock()
196 .await
197 .get(plan_id)
198 .expect("registered plan")
199 .context
200 .clone()
201 }
202
203 pub async fn record_op_state(&self, plan_id: &str, op_id: &str, state: u32) {
207 if let Some(run) = self.inner.lock().await.get_mut(plan_id) {
208 run.op_state.insert(op_id.to_string(), state);
209 }
210 }
211
212 pub async fn get_plan_status_builtin(&self, call: &CapabilityCall) -> CapabilityCallResult {
218 #[derive(Deserialize)]
220 struct Args {
221 plan_id: String,
223 }
224 let args: Args = match serde_json::from_str(&call.args_json) {
225 Ok(a) => a,
226 Err(e) => return error_result(call, format!("invalid get_plan_status args: {e}")),
227 };
228 let plans = self.inner.lock().await;
229 let Some(run) = plans.get(&args.plan_id) else {
230 return error_result(
235 call,
236 format!(
237 "get_plan_status: no active RTDL plan '{}' (it never existed or already finished/cancelled); call get_all_plans to list running plans",
238 args.plan_id
239 ),
240 );
241 };
242 let ops: Vec<serde_json::Value> = run
243 .ops
244 .iter()
245 .map(|op| {
246 let state = run
247 .op_state
248 .get(&op.op_id)
249 .map(|s| state_label(*s))
250 .unwrap_or("pending");
251 serde_json::json!({
252 "op_id": op.op_id,
253 "kind": kind_label(op.node_kind),
254 "description": op.description,
255 "provider_id": op.provider_id,
256 "contract_id": op.contract_id,
257 "state": state,
258 })
259 })
260 .collect();
261 ok_result(
262 call,
263 serde_json::json!({
264 "plan_id": args.plan_id,
265 "running": true,
266 "cancelled": run.cancelled,
267 "ops": ops,
268 })
269 .to_string(),
270 )
271 }
272
273 pub async fn get_all_plans_builtin(&self, call: &CapabilityCall) -> CapabilityCallResult {
277 ok_result(call, self.active_plans_json().await)
278 }
279
280 pub async fn active_plans_json(&self) -> String {
283 let plans = self.inner.lock().await;
284 let mut entries: Vec<(&String, &PlanRun)> = plans.iter().collect();
285 entries.sort_by_key(|(id, _)| id.parse::<u64>().unwrap_or(u64::MAX));
286 let list: Vec<serde_json::Value> = entries
287 .iter()
288 .map(|(id, run)| {
289 serde_json::json!({
290 "plan_id": id,
291 "description": run.description,
292 "op_count": run.ops.len(),
293 "cancelled": run.cancelled,
294 "ops": run.ops.iter().map(|op| serde_json::json!({
295 "op_id": op.op_id,
296 "kind": kind_label(op.node_kind),
297 "description": op.description,
298 "provider_id": op.provider_id,
299 "contract_id": op.contract_id,
300 "state": run.op_state.get(&op.op_id)
301 .map(|state| state_label(*state))
302 .unwrap_or("pending"),
303 })).collect::<Vec<_>>(),
304 })
305 })
306 .collect();
307 serde_json::json!({ "count": list.len(), "plans": list }).to_string()
308 }
309
310 pub async fn complete_plan(&self, plan_id: &str) -> bool {
312 let cancelled = self
313 .inner
314 .lock()
315 .await
316 .remove(plan_id)
317 .is_some_and(|run| run.cancelled);
318 self.changed.notify_waiters();
319 cancelled
320 }
321
322 pub async fn is_cancelled(&self, plan_id: &str) -> bool {
324 self.inner
325 .lock()
326 .await
327 .get(plan_id)
328 .is_some_and(|run| run.cancelled)
329 }
330
331 pub async fn register_or_cancel_async_call(
337 &self,
338 plan_id: &str,
339 call: RunningAsyncCall,
340 ) -> bool {
341 let cancelled_call = {
342 let mut plans = self.inner.lock().await;
343 let Some(run) = plans.get_mut(plan_id) else {
344 return true;
345 };
346 if run.cancelled {
347 Some(call)
348 } else {
349 run.running_async.insert(call.call_id.clone(), call);
350 None
351 }
352 };
353
354 if let Some(call) = cancelled_call {
355 if let Err(error) = call.channel.close().await {
356 warn!("[executor] cancellation remains unconfirmed: {error:#}");
357 }
358 false
359 } else {
360 true
361 }
362 }
363
364 pub async fn unregister_async_call(&self, plan_id: &str, call_id: &str) {
366 if let Some(run) = self.inner.lock().await.get_mut(plan_id) {
367 run.running_async.remove(call_id);
368 }
369 }
370
371 pub async fn cancel_plan_builtin(&self, call: &CapabilityCall) -> CapabilityCallResult {
378 let args: CancelPlanArgs = match serde_json::from_str(&call.args_json) {
379 Ok(args) => args,
380 Err(e) => return error_result(call, format!("invalid cancel_plan args: {e}")),
381 };
382 let (_, output) = self
383 .cancel_plan_control(
384 &args.plan_id,
385 args.wait_ms.unwrap_or(DEFAULT_CANCEL_WAIT_MS),
386 )
387 .await;
388 CapabilityCallResult {
389 call_id: call.call_id.clone(),
390 provider_id: call.provider_id.clone(),
391 contract_id: call.contract_id.clone(),
392 success: true,
393 output,
394 error: String::new(),
395 }
396 }
397
398 pub async fn cancel_plan_control(&self, plan_id: &str, wait_ms: u64) -> (bool, String) {
402 let snapshot = match self.begin_cancel(plan_id).await {
403 Ok(snapshot) => snapshot,
404 Err(_) => {
405 return (
406 true,
407 format!(
408 "RTDL plan '{plan_id}' is not running (already finished or cancelled); nothing to cancel."
409 ),
410 );
411 }
412 };
413 let mut cancel_errors = Vec::new();
414 for running in &snapshot.async_calls {
415 if let Err(error) = running.channel.close().await {
416 warn!(
417 "[executor] cancel_plan async cancel failed for {}: {error:#}",
418 running.call_id
419 );
420 cancel_errors.push(format!("{}: {error:#}", running.call_id));
421 }
422 }
423 let completed = self.wait_until_inactive(plan_id, wait_ms).await
424 && snapshot
425 .async_calls
426 .iter()
427 .all(|call| call.channel.is_closed());
428 let mut message = format!(
429 "Cancellation was requested for RTDL plan '{plan_id}'; cancelled=true, completed={completed}, async_cancel_attempts={}.",
430 snapshot.async_calls.len()
431 );
432 if !cancel_errors.is_empty() {
433 message.push_str(" Some async cancel requests failed: ");
434 message.push_str(&cancel_errors.join("; "));
435 }
436 (completed, message)
437 }
438
439 pub async fn cancel_all_plans(&self) -> bool {
441 let (_, completed) = self
442 .cancel_all_plans_except(None, DEFAULT_CANCEL_WAIT_MS)
443 .await;
444 completed
445 }
446
447 pub async fn cancel_all_plans_except(
450 &self,
451 except_plan_id: Option<&str>,
452 wait_ms: u64,
453 ) -> (usize, bool) {
454 let snapshot = self.begin_cancel_all(except_plan_id).await;
455 let target_count = snapshot.plan_ids.len();
456 let mut confirmed = true;
457 for running in &snapshot.async_calls {
458 if let Err(e) = running.channel.close().await {
459 confirmed = false;
460 warn!(
461 "[executor] cancel_all_plans async cancel failed for {}: {e:#}",
462 running.call_id
463 );
464 }
465 }
466 let completed = self
467 .wait_until_all_inactive(&snapshot.plan_ids, wait_ms)
468 .await;
469 (
470 target_count,
471 completed
472 && confirmed
473 && snapshot
474 .async_calls
475 .iter()
476 .all(|call| call.channel.is_closed()),
477 )
478 }
479
480 async fn begin_cancel(&self, plan_id: &str) -> Result<CancelSnapshot, String> {
486 let mut plans = self.inner.lock().await;
487 let Some(run) = plans.get_mut(plan_id) else {
488 return Err(format!("unknown plan_id '{plan_id}'"));
489 };
490 run.cancelled = true;
491 self.changed.notify_waiters();
492 Ok(CancelSnapshot {
493 async_calls: run
494 .running_async
495 .drain()
496 .map(|(_, running)| running)
497 .collect(),
498 })
499 }
500
501 async fn begin_cancel_all(&self, except_plan_id: Option<&str>) -> CancelAllSnapshot {
505 let mut plans = self.inner.lock().await;
506 let mut async_calls = Vec::new();
507 let mut plan_ids = Vec::new();
508 for (plan_id, run) in plans.iter_mut() {
509 if except_plan_id == Some(plan_id.as_str()) {
510 continue;
511 }
512 run.cancelled = true;
513 plan_ids.push(plan_id.clone());
514 async_calls.extend(run.running_async.drain().map(|(_, running)| running));
515 }
516 self.changed.notify_waiters();
517 CancelAllSnapshot {
518 async_calls,
519 plan_ids,
520 }
521 }
522
523 async fn wait_until_inactive(&self, plan_id: &str, wait_ms: u64) -> bool {
524 self.wait_until_all_inactive(&[plan_id.to_string()], wait_ms)
525 .await
526 }
527
528 async fn wait_until_all_inactive(&self, plan_ids: &[String], wait_ms: u64) -> bool {
530 let wait = async {
531 loop {
532 let notified = self.changed.notified();
533 tokio::pin!(notified);
534 notified.as_mut().enable();
535 let all_inactive = {
536 let plans = self.inner.lock().await;
537 plan_ids.iter().all(|plan_id| !plans.contains_key(plan_id))
538 };
539 if all_inactive {
540 return;
541 }
542 notified.await;
543 }
544 };
545 tokio::time::timeout(Duration::from_millis(wait_ms), wait)
546 .await
547 .is_ok()
548 }
549}
550
551fn error_result(call: &CapabilityCall, error: String) -> CapabilityCallResult {
553 CapabilityCallResult {
554 call_id: call.call_id.clone(),
555 provider_id: call.provider_id.clone(),
556 contract_id: call.contract_id.clone(),
557 success: false,
558 output: String::new(),
559 error,
560 }
561}
562
563fn state_label(state: u32) -> &'static str {
565 match RtdlNodeStateEnum::try_from(state as i32) {
566 Ok(RtdlNodeStateEnum::Pending) => "pending",
567 Ok(RtdlNodeStateEnum::Running) => "running",
568 Ok(RtdlNodeStateEnum::Succeeded) => "succeeded",
569 Ok(RtdlNodeStateEnum::Failed) => "failed",
570 Ok(RtdlNodeStateEnum::Canceled) => "canceled",
571 Ok(RtdlNodeStateEnum::Timeout) => "timeout",
572 Ok(RtdlNodeStateEnum::Paused) => "paused",
573 Ok(RtdlNodeStateEnum::Verifying) => "verifying",
574 _ => "unknown",
575 }
576}
577
578fn kind_label(node_kind: u32) -> &'static str {
580 match node_kind {
581 0 => "sequence",
582 1 => "parallel",
583 2 => "do",
584 3 => "if",
585 4 => "repeat",
586 5 => "while",
587 _ => "unknown",
588 }
589}
590
591fn ok_result(call: &CapabilityCall, output: String) -> CapabilityCallResult {
593 CapabilityCallResult {
594 call_id: call.call_id.clone(),
595 provider_id: call.provider_id.clone(),
596 contract_id: call.contract_id.clone(),
597 success: true,
598 output,
599 error: String::new(),
600 }
601}
602
603#[cfg(test)]
604mod tests {
605 use super::*;
606
607 #[tokio::test]
608 async fn closing_admission_and_registering_a_plan_are_atomic() {
609 let runtime = PlanRuntime::default();
610 let (closed, registered) = tokio::join!(
611 runtime.close_admission(),
612 runtime.register_plan("racing-plan")
613 );
614 assert_ne!(closed.is_ok(), registered.is_ok());
615 if registered.is_ok() {
616 runtime.complete_plan("racing-plan").await;
617 runtime.close_admission().await.unwrap();
618 }
619 assert!(runtime.register_plan("inactive-plan").await.is_err());
620 runtime.open_admission().await;
621 runtime.register_plan("reactivated-plan").await.unwrap();
622 assert!(runtime.close_admission().await.is_err());
623 }
624
625 #[tokio::test]
626 async fn begin_cancel_unknown_plan_fails() {
627 let runtime = PlanRuntime::default();
628 let err = match runtime.begin_cancel("missing").await {
629 Ok(_) => panic!("missing plan should not cancel"),
630 Err(err) => err,
631 };
632 assert!(err.contains("unknown plan_id"));
633 }
634
635 #[tokio::test]
636 async fn registered_plan_starts_uncancelled_then_flips() {
637 let runtime = PlanRuntime::default();
638 runtime.register_plan("p").await.unwrap();
639 assert!(!runtime.is_cancelled("p").await);
640
641 runtime.begin_cancel("p").await.unwrap();
642
643 assert!(runtime.is_cancelled("p").await);
644 }
645
646 #[tokio::test]
647 async fn begin_cancel_all_marks_every_plan() {
648 let runtime = PlanRuntime::default();
649 runtime.register_plan("p1").await.unwrap();
650 runtime.register_plan("p2").await.unwrap();
651 let snapshot = runtime.begin_cancel_all(None).await;
652
653 assert!(snapshot.async_calls.is_empty());
654 assert!(runtime.is_cancelled("p1").await);
655 assert!(runtime.is_cancelled("p2").await);
656 }
657
658 #[tokio::test]
659 async fn begin_cancel_all_excludes_control_plan() {
660 let runtime = PlanRuntime::default();
661 runtime.register_plan("task").await.unwrap();
662 runtime.register_plan("control").await.unwrap();
663
664 let snapshot = runtime.begin_cancel_all(Some("control")).await;
665
666 assert_eq!(snapshot.plan_ids, vec!["task"]);
667 assert!(runtime.is_cancelled("task").await);
668 assert!(!runtime.is_cancelled("control").await);
669 }
670
671 fn status_call(args_json: &str) -> CapabilityCall {
672 CapabilityCall {
673 call_id: "c".into(),
674 provider_id: "executor".into(),
675 contract_id: "robonix/system/executor/builtin/get_plan_status".into(),
676 args_json: args_json.into(),
677 }
678 }
679
680 #[tokio::test]
682 async fn get_plan_status_reports_ops_states() {
683 use crate::pb::pilot::{Plan, RtdlNode};
684 let runtime = PlanRuntime::default();
685 runtime.register_plan("p").await.unwrap();
686 let plan = Plan {
687 plan_id: "p".into(),
688 session_id: "s".into(),
689 round: 0,
690 root_index: 0,
691 nodes: vec![
692 RtdlNode {
693 node_kind: 0,
694 children: vec![1],
695 call: None,
696 op_id: "1".into(),
697 description: "sequence".into(),
698 ..Default::default()
699 },
700 RtdlNode {
701 node_kind: 2,
702 children: vec![],
703 call: Some(CapabilityCall {
704 call_id: "camera-1".into(),
705 provider_id: "realsense_camera".into(),
706 contract_id: "robonix/primitive/camera/capture".into(),
707 args_json: "{}".into(),
708 }),
709 op_id: "2".into(),
710 description: "take snapshot".into(),
711 ..Default::default()
712 },
713 ],
714 };
715 runtime.record_plan_ops(&plan).await;
716 runtime
717 .record_op_state("p", "2", RtdlNodeStateEnum::Running as u32)
718 .await;
719 let r = runtime
720 .get_plan_status_builtin(&status_call(r#"{"plan_id":"p"}"#))
721 .await;
722 assert!(r.success, "{}", r.error);
723 assert!(r.output.contains(r#""op_id":"2""#));
725 assert!(r.output.contains(r#""state":"running""#));
726 assert!(r.output.contains(r#""state":"pending""#));
727 assert!(r.output.contains(r#""running":true"#));
728 assert!(r.output.contains("realsense_camera"));
729 assert!(r.output.contains("robonix/primitive/camera/capture"));
730 }
731
732 #[tokio::test]
733 async fn get_all_plans_lists_active_plans() {
734 let runtime = PlanRuntime::default();
735 let empty = runtime.get_all_plans_builtin(&status_call("{}")).await;
736 assert!(empty.success);
737 assert!(empty.output.contains(r#""count":0"#));
738
739 use crate::pb::pilot::{Plan, RtdlNode};
740 runtime.register_plan("p1").await.unwrap();
741 runtime
742 .record_plan_ops(&Plan {
743 plan_id: "p1".into(),
744 session_id: "s".into(),
745 round: 0,
746 root_index: 0,
747 nodes: vec![RtdlNode {
748 node_kind: 0,
749 children: vec![],
750 call: None,
751 op_id: "1".into(),
752 description: "drive to the kitchen".into(),
753 ..Default::default()
754 }],
755 })
756 .await;
757 runtime.register_plan("p2").await.unwrap();
758 let r = runtime.get_all_plans_builtin(&status_call("{}")).await;
759 assert!(r.success);
760 assert!(r.output.contains(r#""count":2"#));
761 assert!(r.output.contains(r#""plan_id":"p1""#));
762 assert!(r.output.contains(r#""plan_id":"p2""#));
763 assert!(r.output.contains(r#""description":"drive to the kitchen""#));
765 let snapshot = runtime.active_plans_json().await;
766 assert!(snapshot.contains(r#""plan_id":"p1""#));
767 assert!(snapshot.contains(r#""ops""#));
768 }
769
770 #[tokio::test]
771 async fn get_plan_status_unknown_plan_errors() {
772 let runtime = PlanRuntime::default();
773 let r = runtime
774 .get_plan_status_builtin(&status_call(r#"{"plan_id":"missing"}"#))
775 .await;
776 assert!(!r.success);
777 assert!(r.error.contains("no active RTDL plan"));
778 }
779}