Skip to main content

Mountain/RPC/CocoonService/Command/
ExecuteContributedCommand.rs

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