Skip to main content

robonix_executor/dispatch/
async_poll.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2//! Map client-owned capability execution to RTDL progress and results.
3
4use crate::pb::pilot::rtdl_node_state::RtdlNodeStateEnum;
5use crate::pb::pilot::{CapabilityCall, CapabilityCallResult};
6use crate::plan_runtime::{PlanRuntime, RunningAsyncCall};
7use crate::rtdl_wire::NodeEventContext;
8use robonix_atlas::client::channel::Channel;
9use std::time::Duration;
10
11/// The channel owns protocol and execution lifetime; Executor owns RTDL events.
12pub async fn run_until_terminal(
13    call: &CapabilityCall,
14    channel: &Channel,
15    node: &NodeEventContext,
16    runtime: &PlanRuntime,
17) -> (CapabilityCallResult, u32) {
18    let execution = async {
19        let args = serde_json::from_str(&call.args_json)?;
20        if channel.is_async() {
21            let accepted = runtime
22                .register_or_cancel_async_call(
23                    &node.plan_id,
24                    RunningAsyncCall {
25                        call_id: call.call_id.clone(),
26                        channel: channel.clone(),
27                    },
28                )
29                .await;
30            if !accepted {
31                anyhow::ensure!(
32                    channel.is_closed(),
33                    "cancellation remains unconfirmed; channel {} retained",
34                    channel.channel_id
35                );
36                return Ok((
37                    serde_json::json!({"detail": "plan was cancelled"}),
38                    RtdlNodeStateEnum::Canceled as u32,
39                ));
40            }
41        }
42        let initial = channel.call(args).await?;
43        if channel.is_terminal() {
44            channel.close().await?;
45            let state = if channel.is_async()
46                && initial.get("accepted") == Some(&serde_json::Value::Bool(false))
47            {
48                RtdlNodeStateEnum::Failed
49            } else {
50                RtdlNodeStateEnum::Succeeded
51            };
52            return Ok::<_, anyhow::Error>((initial, state as u32));
53        }
54        loop {
55            if runtime.is_cancelled(&node.plan_id).await {
56                channel.close().await?;
57                return Ok((
58                    serde_json::json!({"detail": "plan was cancelled"}),
59                    RtdlNodeStateEnum::Canceled as u32,
60                ));
61            }
62            let status = tokio::time::timeout(Duration::from_secs(30), channel.status()).await??;
63            let state = parse_state_name(status["state"].as_str().unwrap_or_default())
64                .ok_or_else(|| anyhow::anyhow!("invalid status response: {status}"))?;
65            if crate::rtdl_wire::is_terminal_state(state) {
66                channel.close().await?;
67                return Ok((status, state));
68            }
69            runtime
70                .record_op_state(&node.plan_id, &node.op_id, state)
71                .await;
72            tokio::time::sleep(Duration::from_secs(2)).await;
73        }
74    }
75    .await;
76    runtime
77        .unregister_async_call(&node.plan_id, &call.call_id)
78        .await;
79    match execution {
80        Ok((output, state)) => {
81            let success = state == RtdlNodeStateEnum::Succeeded as u32;
82            (
83                CapabilityCallResult {
84                    call_id: call.call_id.clone(),
85                    provider_id: call.provider_id.clone(),
86                    contract_id: call.contract_id.clone(),
87                    success,
88                    output: if success {
89                        output.to_string()
90                    } else {
91                        String::new()
92                    },
93                    error: if success {
94                        String::new()
95                    } else {
96                        output["detail"].as_str().unwrap_or_default().to_owned()
97                    },
98                },
99                state,
100            )
101        }
102        Err(error) => {
103            let cleanup = if channel.is_terminal() {
104                channel.close().await.err()
105            } else {
106                None
107            };
108            (
109                super::error_result(
110                    call,
111                    format!(
112                        "{error:#}; execution channel {}; cleanup: {cleanup:?}",
113                        channel.channel_id
114                    ),
115                ),
116                RtdlNodeStateEnum::Failed as u32,
117            )
118        }
119    }
120}
121
122pub fn parse_state_name(s: &str) -> Option<u32> {
123    Some(match s.to_ascii_uppercase().as_str() {
124        "PENDING" => RtdlNodeStateEnum::Pending,
125        "RUNNING" => RtdlNodeStateEnum::Running,
126        "SUCCEEDED" => RtdlNodeStateEnum::Succeeded,
127        "FAILED" => RtdlNodeStateEnum::Failed,
128        "CANCELED" | "CANCELLED" => RtdlNodeStateEnum::Canceled,
129        "TIMEOUT" => RtdlNodeStateEnum::Timeout,
130        "PAUSED" => RtdlNodeStateEnum::Paused,
131        _ => return None,
132    } as u32)
133}
浙ICP备2023005800号-2 浙公网安备33010902005384号