Skip to main content

Mountain/RPC/CocoonService/Command/
ExecuteContributedCommand.rs

1//! Look up a contributed command and execute it. Marshals the first
2//! protobuf `argument` oneof into `serde_json::Value` for the executor.
3
4use CommonLibrary::Command::CommandExecutor::CommandExecutor;
5use serde_json::json;
6use tonic::{Response, Status};
7
8use crate::{
9	RPC::CocoonService::CocoonServiceImpl,
10	Vine::Generated::{ExecuteCommandRequest, ExecuteCommandResponse, RpcError, argument, execute_command_response},
11	dev_log,
12};
13
14pub async fn Fn(
15	Service:&CocoonServiceImpl,
16
17	Request:ExecuteCommandRequest,
18) -> Result<Response<ExecuteCommandResponse>, Status> {
19	dev_log!(
20		"cocoon",
21		"[CocoonService] Executing command '{}' with {} arguments",
22		Request.command_id,
23		Request.arguments.len()
24	);
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
48			Ok(Response::new(ExecuteCommandResponse {
49				result:Some(execute_command_response::Result::Value(Bytes)),
50			}))
51		},
52
53		Err(Error) => {
54			let Bytes = serde_json::to_vec(&Error.to_string()).unwrap_or_default();
55
56			Ok(Response::new(ExecuteCommandResponse {
57				result:Some(execute_command_response::Result::Error(RpcError {
58					code:-32000,
59					message:Error.to_string(),
60					data:Bytes,
61				})),
62			}))
63		},
64	}
65}