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};
7use ::Vine::Generated::{ExecuteCommandRequest, ExecuteCommandResponse, RpcError, argument, execute_command_response};
8
9use crate::{RPC::CocoonService::CocoonServiceImpl, dev_log};
10
11pub async fn Fn(
12	Service:&CocoonServiceImpl,
13
14	Request:ExecuteCommandRequest,
15) -> Result<Response<ExecuteCommandResponse>, Status> {
16	dev_log!(
17		"cocoon",
18		"[CocoonService] Executing command '{}' with {} arguments",
19		Request.command_id,
20		Request.arguments.len()
21	);
22
23	for (Index, Argument) in Request.arguments.iter().enumerate() {
24		dev_log!("cocoon", "[CocoonService] Argument {}: {:?}", Index, Argument);
25	}
26
27	let Arg:serde_json::Value = Request
28		.arguments
29		.first()
30		.and_then(|A| A.value.as_ref())
31		.map(|V| {
32			match V {
33				argument::Value::StringValue(S) => json!(S),
34				argument::Value::IntValue(I) => json!(I),
35				argument::Value::BoolValue(B) => json!(B),
36				argument::Value::BytesValue(Bytes) => serde_json::from_slice(Bytes).unwrap_or(serde_json::Value::Null),
37			}
38		})
39		.unwrap_or(serde_json::Value::Null);
40
41	match Service.environment.ExecuteCommand(Request.command_id, Arg).await {
42		Ok(Value) => {
43			let Bytes = serde_json::to_vec(&Value).unwrap_or_default();
44
45			Ok(Response::new(ExecuteCommandResponse {
46				result:Some(execute_command_response::Result::Value(Bytes)),
47			}))
48		},
49
50		Err(Error) => {
51			let Bytes = serde_json::to_vec(&Error.to_string()).unwrap_or_default();
52
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}