reactive_graph_command_model/entity/
command.rs

1use std::collections::HashMap;
2use std::ops::Deref;
3use std::ops::DerefMut;
4
5use serde_json::Value;
6
7use crate::builder::CommandDefinition;
8use crate::builder::CommandDefinitionBuilder;
9use crate::entity::arg::CommandArgs;
10use crate::error::CommandArgsError;
11use crate::error::CommandExecutionFailed;
12use crate::error::NotACommand;
13use crate::reactive_graph::command::command::COMMAND;
14use crate::reactive_graph::command::command::CommandProperties;
15use reactive_graph_graph::ComponentContainer;
16use reactive_graph_graph::ComponentTypeIds;
17use reactive_graph_graph::DataType;
18use reactive_graph_graph::EntityType;
19use reactive_graph_graph::EntityTypeId;
20use reactive_graph_graph::Mutability;
21use reactive_graph_graph::PropertyInstanceGetter;
22use reactive_graph_graph::PropertyInstanceSetter;
23use reactive_graph_graph::PropertyType;
24use reactive_graph_graph::SocketType;
25use reactive_graph_model_core::reactive_graph::core::action::ACTION;
26use reactive_graph_model_core::reactive_graph::core::action::ActionProperties;
27use reactive_graph_model_core::reactive_graph::core::labeled::LABELED;
28use reactive_graph_model_core::reactive_graph::core::labeled::LabeledProperties;
29use reactive_graph_reactive_model_api::ReactivePropertyContainer;
30use reactive_graph_reactive_model_impl::ReactiveEntity;
31
32pub struct Command(ReactiveEntity);
33
34impl Command {}
35
36impl Command {
37    pub fn new(entity: ReactiveEntity) -> Result<Self, NotACommand> {
38        if !entity.is_a(&ACTION) || !entity.is_a(&COMMAND) {
39            return Err(NotACommand);
40        }
41        Ok(Command(entity))
42    }
43
44    pub fn new_unchecked(entity: ReactiveEntity) -> Self {
45        Self(entity)
46    }
47
48    pub fn builder() -> CommandDefinitionBuilder {
49        CommandDefinition::builder()
50    }
51
52    pub fn get_entity_type(&self) -> EntityType {
53        let components = ComponentTypeIds::new()
54            .component(LABELED.deref())
55            .component(ACTION.deref())
56            .component(COMMAND.deref());
57        if let Some(args) = self.get(CommandProperties::ARGS.as_ref()).and_then(|args| CommandArgs::try_from(args).ok()) {
58            let properties = CommandProperties::property_types();
59            for arg in args.to_vec() {
60                if !properties.contains_key(&arg.name) {
61                    properties.insert(
62                        arg.name.clone(),
63                        PropertyType::builder()
64                            .name(arg.name.clone())
65                            .description(arg.help.unwrap_or_default())
66                            .data_type(DataType::Any)
67                            .socket_type(SocketType::Input)
68                            .mutability(Mutability::Mutable)
69                            .build(),
70                    );
71                }
72            }
73        }
74        EntityType::builder()
75            .ty(self.0.ty.clone())
76            .description(self.0.description.clone())
77            .components(components)
78            .properties(CommandProperties::property_types().clone())
79            .build()
80    }
81
82    /// Executes a command
83    pub fn execute(&self) -> Result<Option<Value>, CommandExecutionFailed> {
84        if !self.0.is_a(&ACTION) || !self.0.is_a(&COMMAND) {
85            return Err(CommandExecutionFailed::NotACommand);
86        }
87        self.0.set(ActionProperties::TRIGGER.as_ref(), Value::Bool(true));
88        Ok(self.0.get(CommandProperties::CMD_RESULT.as_ref()))
89    }
90
91    /// Executes a command with the given arguments
92    /// Stores the command result in the command result property
93    pub fn execute_with_args(&self, args: HashMap<String, Value>) -> Result<Option<Value>, CommandExecutionFailed> {
94        if !self.0.is_a(&ACTION) || !self.0.is_a(&COMMAND) {
95            return Err(CommandExecutionFailed::NotACommand);
96        }
97        // Check that all given arguments are valid arguments and the properties exists
98        match self.args() {
99            Ok(command_args) => {
100                for property_name in args.keys() {
101                    if !command_args.contains(property_name.clone()) {
102                        return Err(CommandExecutionFailed::InvalidArgument(property_name.clone()));
103                    } else if !self.0.has_property(property_name) {
104                        return Err(CommandExecutionFailed::MissingArgumentProperty(property_name.clone()));
105                    }
106                }
107                for command_arg in command_args.to_vec() {
108                    if command_arg.required && !args.contains_key(&command_arg.name) {
109                        return Err(CommandExecutionFailed::MissingMandatoryArgument(command_arg.name));
110                    }
111                }
112            }
113            Err(e) => {
114                return Err(CommandExecutionFailed::CommandArgsError(e));
115            }
116        }
117        for (property_name, value) in args {
118            if self.0.has_property(&property_name) {
119                self.0.set_checked(&property_name, value)
120            }
121        }
122        match self.execute() {
123            Ok(Some(result)) => {
124                self.0.set(CommandProperties::CMD_RESULT.as_ref(), result.clone());
125                Ok(Some(result))
126            }
127            Ok(None) => Ok(None),
128            Err(e) => Err(e),
129        }
130    }
131
132    pub fn namespace(&self) -> Option<String> {
133        self.0.as_string(CommandProperties::NAMESPACE.as_ref())
134    }
135
136    pub fn name(&self) -> Option<String> {
137        self.0.as_string(CommandProperties::COMMAND.as_ref())
138    }
139
140    pub fn label(&self) -> Option<String> {
141        self.0.as_string(LabeledProperties::LABEL.as_ref())
142    }
143
144    pub fn args(&self) -> Result<CommandArgs, CommandArgsError> {
145        match self.0.get(CommandProperties::ARGS.as_ref()) {
146            Some(v) => CommandArgs::try_from(v),
147            None => Err(CommandArgsError::CommandArgDefinitionMissing),
148        }
149    }
150
151    pub fn command(&self) -> Option<clap::Command> {
152        let name = self.name()?;
153        let Ok(args) = self.args() else {
154            return None;
155        };
156        Some(clap::Command::new(name).args(args.as_args()))
157    }
158
159    pub fn help(&self) -> Option<String> {
160        self.0.as_string(CommandProperties::HELP.as_ref())
161    }
162
163    pub fn ty(&self) -> EntityTypeId {
164        self.0.ty.clone()
165    }
166
167    // TODO: impl Deref instead
168    pub fn get_instance(&self) -> ReactiveEntity {
169        self.0.clone()
170    }
171}
172
173impl Deref for Command {
174    type Target = ReactiveEntity;
175
176    fn deref(&self) -> &Self::Target {
177        &self.0
178    }
179}
180
181impl DerefMut for Command {
182    fn deref_mut(&mut self) -> &mut Self::Target {
183        &mut self.0
184    }
185}
186
187impl TryFrom<ReactiveEntity> for Command {
188    type Error = NotACommand;
189
190    fn try_from(entity: ReactiveEntity) -> Result<Self, Self::Error> {
191        Command::new(entity)
192    }
193}
194
195// pub fn command_property_types() -> PropertyTypes {
196//     PropertyTypes::new()
197//         .property(
198//             PropertyType::builder()
199//                 .name(LABEL.property_name())
200//                 .data_type(DataType::String)
201//                 .mutability(Immutable)
202//                 .build()
203//         )
204//         .property(PropertyType::bool(TRIGGER.property_name()))
205//         .property(
206//             PropertyType::builder()
207//                 .name(COMMAND_NAMESPACE.property_name())
208//                 .data_type(DataType::String)
209//                 .mutability(Immutable)
210//                 .build()
211//         )
212//         .property(
213//             PropertyType::builder()
214//                 .name(COMMAND_NAME.property_name())
215//                 .data_type(DataType::String)
216//                 .mutability(Immutable)
217//                 .build()
218//         )
219//         .property(PropertyType::object(COMMAND_ARGS.property_name()))
220//         .property(
221//             PropertyType::builder()
222//                 .name(COMMAND_HELP.property_name())
223//                 .data_type(DataType::String)
224//                 .mutability(Immutable)
225//                 .build()
226//         )
227//         .property(
228//             PropertyType::builder()
229//                 .name(COMMAND_RESULT.property_name())
230//                 .data_type(DataType::Any)
231//                 .build()
232//         )
233// }
234
235#[cfg(test)]
236mod tests {
237    use serde_json::json;
238    use std::collections::HashMap;
239    use std::ops::Deref;
240    use std::str::FromStr;
241    use uuid::Uuid;
242
243    use reactive_graph_graph::ComponentTypeIds;
244    use reactive_graph_graph::PropertyInstances;
245    use reactive_graph_reactive_model_impl::ReactiveEntity;
246    use reactive_graph_reactive_model_impl::ReactiveProperties;
247
248    use crate::entity::Command;
249    use crate::error::CommandExecutionFailed;
250    use crate::reactive_graph::command::command::COMMAND;
251    use crate::reactive_graph::command::command::CommandProperties;
252    use reactive_graph_graph::EntityTypeId;
253    use reactive_graph_graph::PropertyInstanceGetter;
254    use reactive_graph_graph::PropertyInstanceSetter;
255    use reactive_graph_model_core::reactive_graph::core::action::ACTION;
256    use reactive_graph_model_core::reactive_graph::core::action::ActionProperties;
257    use reactive_graph_reactive_model_api::ReactivePropertyContainer;
258
259    #[test]
260    fn test_command() {
261        let ty = EntityTypeId::from_str("test::Test").unwrap();
262        let reactive_entity = ReactiveEntity::builder().ty(&ty).build();
263        assert!(Command::try_from(reactive_entity).is_err());
264
265        let components = ComponentTypeIds::new().component(ACTION.deref()).component(COMMAND.deref());
266        let properties = PropertyInstances::new()
267            .property(ActionProperties::TRIGGER, json!(false))
268            .property("arg1", json!(0))
269            .property("arg2", json!(1))
270            .property(CommandProperties::CMD_RESULT, json!(0))
271            .property(CommandProperties::COMMAND, json!("hello_command"))
272            .property(
273                CommandProperties::ARGS,
274                json!([
275                    {
276                        "name": "arg1"
277                    },
278                    {
279                        "name": "arg2",
280                        "required": true
281                    }
282                ]),
283            )
284            .property(CommandProperties::HELP, json!("Help text"));
285
286        let id = Uuid::new_v4();
287        let reactive_properties = ReactiveProperties::new_with_id_from_properties(id, properties);
288        let reactive_entity = ReactiveEntity::builder()
289            .ty(&ty)
290            .id(id)
291            .components(components)
292            .properties(reactive_properties)
293            .build();
294        let e1 = reactive_entity.clone();
295        let e2 = reactive_entity.clone();
296        e1.observe_with_handle(
297            &ActionProperties::TRIGGER.as_ref(),
298            move |_| {
299                let arg1 = e2.as_u64("arg1").unwrap_or_default();
300                let arg2 = e2.as_u64("arg2").unwrap_or_default();
301                e2.set(CommandProperties::CMD_RESULT.as_ref(), json!(arg1 + arg2));
302            },
303            0,
304        );
305        let command = Command::new(reactive_entity).expect("Failed to create a command");
306        assert_eq!("hello_command", command.name().expect("Failed to get command name"));
307        assert_eq!("Help text", command.help().expect("Failed to get help text"));
308        assert_eq!(0, e1.as_u64(CommandProperties::CMD_RESULT.as_ref()).expect("Failed to get initial result"));
309        command.execute().expect("Command execution failed");
310        assert_eq!(1, e1.as_u64(CommandProperties::CMD_RESULT.as_ref()).expect("Failed to get changed result"));
311        let mut args = HashMap::new();
312        args.insert(String::from("arg1"), json!(1));
313        args.insert(String::from("arg2"), json!(2));
314        let _ = command.execute_with_args(args).expect("Failed to execute command with args");
315        assert_eq!(3, e1.as_u64(CommandProperties::CMD_RESULT.as_ref()).expect("Failed to get changed result"));
316        let mut args = HashMap::new();
317        args.insert(String::from("arg1"), json!(1));
318        args.insert(String::from("arg2"), json!(2));
319        args.insert(String::from("arg3"), json!(3));
320        assert_eq!(CommandExecutionFailed::InvalidArgument(String::from("arg3")), command.execute_with_args(args).unwrap_err());
321        let mut args = HashMap::new();
322        args.insert(String::from("arg1"), json!(1));
323        assert_eq!(
324            CommandExecutionFailed::MissingMandatoryArgument(String::from("arg2")),
325            command.execute_with_args(args).unwrap_err()
326        );
327    }
328}