Skip to main content

Mountain/RPC/CocoonService/Command/
ExecuteContributedCommand.rs

1#![allow(non_snake_case)]
2
3//! Look up a contributed command and execute it. Marshals the first
4//! protobuf `argument` oneof into `serde_json::Value` for the executor.
5
6use CommonLibrary::Command::CommandExecutor::CommandExecutor;
7use serde_json::json;
8use tonic::{Response, Status};
9
10use crate::{
11	RPC::CocoonService::CocoonServiceImpl,
12	Vine::Generated::{ExecuteCommandRequest, ExecuteCommandResponse, RpcError, argument, execute_command_response},
13	dev_log,
14};
15
16pub async fn Fn(
17	Service:&CocoonServiceImpl,
18	Request:ExecuteCommandRequest,
19) -> Result<Response<ExecuteCommandResponse>, Status> {
20	dev_log!(
21		"cocoon",
22		"[CocoonService] Executing command '{}' with {} arguments",
23		Request.command_id,
24		Request.arguments.len()
25	);
26	for (Index, Argument) in Request.arguments.iter().enumerate() {
27		dev_log!("cocoon", "[CocoonService] Argument {}: {:?}", Index, Argument);
28	}
29
30	let Arg:serde_json::Value = Request
31		.arguments
32		.first()
33		.and_then(|A| A.value.as_ref())
34		.map(|V| {
35			match V {
36				argument::Value::StringValue(S) => json!(S),
37				argument::Value::IntValue(I) => json!(I),
38				argument::Value::BoolValue(B) => json!(B),
39				argument::Value::BytesValue(Bytes) => serde_json::from_slice(Bytes).unwrap_or(serde_json::Value::Null),
40			}
41		})
42		.unwrap_or(serde_json::Value::Null);
43
44	match Service.environment.ExecuteCommand(Request.command_id, Arg).await {
45		Ok(Value) => {
46			let Bytes = serde_json::to_vec(&Value).unwrap_or_default();
47			Ok(Response::new(ExecuteCommandResponse {
48				result:Some(execute_command_response::Result::Value(Bytes)),
49			}))
50		},
51		Err(Error) => {
52			let Bytes = serde_json::to_vec(&Error.to_string()).unwrap_or_default();
53			Ok(Response::new(ExecuteCommandResponse {
54				result:Some(execute_command_response::Result::Error(RpcError {
55					code:-32000,
56					message:Error.to_string(),
57					data:Bytes,
58				})),
59			}))
60		},
61	}
62}