Skip to main content

robonix_executor/
grpc_server.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// Author: wheatfox <wheatfox17@icloud.com>
3//! Executor gRPC entry points for execution, plan control, queries, and health.
4use crate::active_plans::PlanRuntime;
5use crate::pb::contracts::robonix_system_executor_cancel_all_plans_server::RobonixSystemExecutorCancelAllPlans;
6use crate::pb::contracts::robonix_system_executor_control_plan_server::RobonixSystemExecutorControlPlan;
7use crate::pb::contracts::robonix_system_executor_execute_server::RobonixSystemExecutorExecute;
8use crate::pb::contracts::robonix_system_executor_execute_stream_server::RobonixSystemExecutorExecuteStream;
9use crate::pb::contracts::robonix_system_executor_get_health_server::RobonixSystemExecutorGetHealth;
10use crate::pb::contracts::robonix_system_executor_list_active_plans_server::RobonixSystemExecutorListActivePlans;
11use crate::pb::executor::ExecuteStreamInput;
12use crate::pb::executor::{
13    CancelAllResponse, ControlPlanResponse, ListActivePlansResponse, RtdlEvent,
14};
15use crate::pb::module_health::{
16    GetModuleHealthRequest, GetModuleHealthResponse, ModuleHealth, ModuleHealthReport,
17};
18use crate::pb::pilot::Plan;
19use crate::plan_input::PlanInput;
20use crate::plan_scheduler::PlanScheduler;
21use crate::verification::VerificationPolicy;
22use robonix_atlas::client::AtlasClient;
23use std::sync::Arc;
24use tokio_stream::wrappers::ReceiverStream;
25use tonic::{Request, Response, Status, Streaming};
26
27const MODULE_HEALTH_SCHEMA_VERSION: u32 = 1;
28const MODULE_HEALTH_OK: u32 = 0;
29const MODULE_HEALTH_TTL_MS: u32 = 5000;
30
31/// Executor gRPC handlers sharing active plans and result verification policy.
32///
33/// `AtlasClient` is cheap to clone — each Execute RPC clones it so per-plan
34/// dispatch runs without serialising on a single mutex.
35#[derive(Clone)]
36pub struct ExecutorServiceImpl {
37    /// Atlas connection used to resolve capabilities for execution and cancellation.
38    pub(crate) atlas: AtlasClient,
39    /// Executor's own provider_id. Two roles:
40    ///   1. consumer_id passed to atlas on every ConnectCapability so the
41    ///      channel record reflects who is using each downstream provider.
42    ///   2. self-detection: when a CapabilityCall in the plan targets this
43    ///      provider_id, dispatch short-circuits to the in-process builtin
44    ///      handlers instead of going through MCP loopback.
45    pub(crate) provider_id: String,
46    /// Shared plan progress and cancellation state used by all RPC handlers.
47    pub(crate) runtime: PlanRuntime,
48    /// Immutable verification timing and routing rules applied to submitted plans.
49    pub(crate) verification: Arc<VerificationPolicy>,
50}
51
52impl ExecutorServiceImpl {
53    /// Assemble RPC handlers sharing one active-plan table and verification policy.
54    pub fn new(
55        atlas: AtlasClient,
56        provider_id: String,
57        verification: Arc<VerificationPolicy>,
58    ) -> Self {
59        Self {
60            atlas,
61            provider_id,
62            runtime: PlanRuntime::default(),
63            verification,
64        }
65    }
66}
67
68#[tonic::async_trait]
69impl RobonixSystemExecutorExecute for ExecutorServiceImpl {
70    type ExecuteStream = ReceiverStream<Result<RtdlEvent, Status>>;
71
72    /// Validate and reserve a plan before returning headers, then stream its execution.
73    async fn execute(
74        &self,
75        request: Request<Plan>,
76    ) -> Result<Response<Self::ExecuteStream>, Status> {
77        let input = PlanInput::from_plan(request.into_inner()).map_err(Status::invalid_argument)?;
78        Ok(Response::new(
79            PlanScheduler::start(
80                self.atlas.clone(),
81                self.provider_id.clone(),
82                self.runtime.clone(),
83                self.verification.clone(),
84                input,
85                tokio_stream::empty(),
86            )
87            .await?,
88        ))
89    }
90}
91
92#[tonic::async_trait]
93impl RobonixSystemExecutorExecuteStream for ExecutorServiceImpl {
94    type ExecuteStreamStream = ReceiverStream<Result<RtdlEvent, Status>>;
95
96    /// Require START before handing incremental input to the common execution loop.
97    async fn execute_stream(
98        &self,
99        request: Request<Streaming<ExecuteStreamInput>>,
100    ) -> Result<Response<Self::ExecuteStreamStream>, Status> {
101        let mut stream = request.into_inner();
102        let mut admission = self.runtime.subscribe_admission();
103        // An idle input stream must not keep graceful shutdown waiting for START.
104        let first = tokio::select! {
105            _ = admission.wait_for(|closed| *closed) => {
106                return Err(Status::failed_precondition("Executor is not accepting plans; activate it before executing"));
107            }
108            message = stream.message() => message?.ok_or_else(|| Status::invalid_argument("missing START"))?,
109        };
110        let mut input = PlanInput::default();
111        input.accept(first).map_err(Status::invalid_argument)?;
112        Ok(Response::new(
113            PlanScheduler::start(
114                self.atlas.clone(),
115                self.provider_id.clone(),
116                self.runtime.clone(),
117                self.verification.clone(),
118                input,
119                stream,
120            )
121            .await?,
122        ))
123    }
124}
125
126#[tonic::async_trait]
127impl RobonixSystemExecutorCancelAllPlans for ExecutorServiceImpl {
128    /// Cancel active plans and return whether they finished within the default wait.
129    async fn cancel_all(
130        &self,
131        _request: Request<crate::pb::executor::CancelAllRequest>,
132    ) -> Result<Response<CancelAllResponse>, Status> {
133        let success = self.runtime.cancel_all_plans().await;
134        Ok(Response::new(CancelAllResponse { success }))
135    }
136}
137
138#[tonic::async_trait]
139impl RobonixSystemExecutorListActivePlans for ExecutorServiceImpl {
140    /// Return a snapshot without creating an execution plan for the query.
141    async fn list_active_plans(
142        &self,
143        _request: Request<crate::pb::executor::ListActivePlansRequest>,
144    ) -> Result<Response<ListActivePlansResponse>, Status> {
145        Ok(Response::new(ListActivePlansResponse {
146            success: true,
147            plans_json: self.runtime.active_plans_json().await,
148            error: String::new(),
149        }))
150    }
151}
152
153#[tonic::async_trait]
154impl RobonixSystemExecutorControlPlan for ExecutorServiceImpl {
155    /// Apply a cancel or cancel_all request and report completion within its wait limit.
156    async fn control_plan(
157        &self,
158        request: Request<crate::pb::executor::ControlPlanRequest>,
159    ) -> Result<Response<ControlPlanResponse>, Status> {
160        let request = request.into_inner();
161        let response = match request.action.as_str() {
162            "cancel" => {
163                let wait_ms = if request.wait_ms == 0 {
164                    5_000
165                } else {
166                    request.wait_ms
167                };
168                let (completed, message) = self
169                    .runtime
170                    .cancel_plan_control(&request.plan_id, wait_ms)
171                    .await;
172                ControlPlanResponse {
173                    success: true,
174                    completed,
175                    message,
176                    error: String::new(),
177                }
178            }
179            "cancel_all" => {
180                let wait_ms = if request.wait_ms == 0 {
181                    5_000
182                } else {
183                    request.wait_ms
184                };
185                let (target_count, completed) =
186                    self.runtime.cancel_all_plans_except(None, wait_ms).await;
187                ControlPlanResponse {
188                    success: true,
189                    completed,
190                    message: format!(
191                        "Cancellation requested for all RTDL plans; target_count={target_count}, completed={completed}."
192                    ),
193                    error: String::new(),
194                }
195            }
196            action => ControlPlanResponse {
197                success: false,
198                completed: true,
199                message: String::new(),
200                error: format!("unknown plan-control action '{action}'"),
201            },
202        };
203        Ok(Response::new(response))
204    }
205}
206
207#[tonic::async_trait]
208impl RobonixSystemExecutorGetHealth for ExecutorServiceImpl {
209    /// Report the health of the running Executor service.
210    async fn get_module_health(
211        &self,
212        _request: Request<GetModuleHealthRequest>,
213    ) -> Result<Response<GetModuleHealthResponse>, Status> {
214        Ok(Response::new(GetModuleHealthResponse {
215            report: Some(executor_health_report(
216                &self.provider_id,
217                self.runtime.is_accepting_plans(),
218            )),
219        }))
220    }
221}
222
223/// Build the minimal module-health report served to Vitals.
224fn executor_health_report(provider_id: &str, accepting_plans: bool) -> ModuleHealthReport {
225    ModuleHealthReport {
226        schema_version: MODULE_HEALTH_SCHEMA_VERSION,
227        module: Some(ModuleHealth {
228            module_key: String::new(),
229            module_id: "executor".to_string(),
230            provider_id: provider_id.to_string(),
231            health: MODULE_HEALTH_OK,
232            state: if accepting_plans {
233                "active"
234            } else {
235                "inactive"
236            }
237            .to_string(),
238            reason_code: "OK".to_string(),
239            detail: "executor serving".to_string(),
240            source: String::new(),
241            received_ts_ns: 0,
242            ttl_ms: MODULE_HEALTH_TTL_MS,
243        }),
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    /// Health responses retain the minimal schema and the configured provider identity.
252    #[test]
253    fn executor_health_report_uses_minimal_module_health_v1_fields() {
254        let report = executor_health_report("executor", true);
255        assert_eq!(report.schema_version, MODULE_HEALTH_SCHEMA_VERSION);
256
257        let module = report.module.expect("module health");
258        assert_eq!(module.module_id, "executor");
259        assert_eq!(module.provider_id, "executor");
260        assert_eq!(module.health, MODULE_HEALTH_OK);
261        assert_eq!(module.state, "active");
262        assert_eq!(module.reason_code, "OK");
263        assert_eq!(module.detail, "executor serving");
264        assert_eq!(module.ttl_ms, MODULE_HEALTH_TTL_MS);
265
266        assert!(module.module_key.is_empty());
267        assert!(module.source.is_empty());
268        assert_eq!(module.received_ts_ns, 0);
269    }
270}
浙ICP备2023005800号-2 浙公网安备33010902005384号