Skip to main content

loco_rs/
task.rs

1//! # Task Management Module
2//!
3//! This module defines the task management framework used to manage and execute
4//! tasks in a web server application.
5use std::collections::BTreeMap;
6
7use async_trait::async_trait;
8
9use crate::{app::AppContext, errors::Error, Result};
10
11/// Struct representing a collection of task arguments.
12///
13/// A task sees its command line two ways. Pick one per task:
14///
15/// * [`Vars::cli_arg`] / [`Vars::cli`]: the `key:value` tokens, parsed for you.
16/// * [`Vars::args`]: every token, verbatim and in order. Feed it to `clap`, or
17///   use it as a file list (`cargo loco task import *.csv`).
18///
19/// A token such as `C:\data.csv` contains a colon, so it shows up in `cli` as
20/// well as in `args()`. Tasks that take free-form arguments should read only
21/// `args()`.
22#[derive(Default, Debug)]
23#[non_exhaustive]
24pub struct Vars {
25    /// The `key:value` cli arguments.
26    pub cli: BTreeMap<String, String>,
27    args: Vec<String>,
28}
29
30impl Vars {
31    /// Create [`Vars`] instance from cli arguments.
32    ///
33    /// # Arguments
34    ///
35    /// * `key` - A string representing the key.
36    /// * `value` - A string representing the value.
37    ///
38    /// # Example
39    ///
40    /// ```
41    /// use loco_rs::task::Vars;
42    ///
43    /// let args = vec![("key1".to_string(), "value".to_string())];
44    /// let vars = Vars::from_cli_args(args);
45    /// ```
46    #[must_use]
47    pub fn from_cli_args(args: Vec<(String, String)>) -> Self {
48        Self {
49            args: args.iter().map(|(k, v)| format!("{k}:{v}")).collect(),
50            cli: args.into_iter().collect(),
51        }
52    }
53
54    /// Create [`Vars`] from the raw tokens given after the task name.
55    ///
56    /// Every token is kept verbatim for [`Vars::args`]. Tokens of the form
57    /// `key:value` are additionally available through [`Vars::cli_arg`];
58    /// anything else (a glob result, a flag, a path) is not an error.
59    ///
60    /// # Example
61    ///
62    /// ```
63    /// use loco_rs::task::Vars;
64    ///
65    /// let vars = Vars::from_args(vec!["a.txt".to_string(), "mode:fast".to_string()]);
66    /// assert_eq!(vars.args(), ["a.txt", "mode:fast"]);
67    /// assert_eq!(vars.cli_arg("mode").unwrap(), "fast");
68    /// ```
69    #[must_use]
70    pub fn from_args(args: Vec<String>) -> Self {
71        let cli = args
72            .iter()
73            .filter_map(|a| a.split_once(':'))
74            .filter(|(k, _)| !k.is_empty())
75            .map(|(k, v)| (k.to_string(), v.to_string()))
76            .collect();
77        Self { cli, args }
78    }
79
80    /// Every argument given after the task name, verbatim and in order.
81    ///
82    /// # Example
83    ///
84    /// ```
85    /// use loco_rs::task::Vars;
86    ///
87    /// let vars = Vars::from_args(vec!["--dry-run".to_string(), "a.txt".to_string()]);
88    /// assert_eq!(vars.args(), ["--dry-run", "a.txt"]);
89    /// ```
90    #[must_use]
91    pub fn args(&self) -> &[String] {
92        &self.args
93    }
94
95    /// Retrieves the value associated with the given key from the `cli` list.
96    ///
97    /// # Errors
98    ///
99    /// Returns an error if the key does not exist.
100    ///
101    /// # Example
102    ///
103    /// ```
104    /// use loco_rs::task::Vars;
105    ///
106    /// let args = vec![("key1".to_string(), "value".to_string())];
107    /// let vars = Vars::from_cli_args(args);
108    ///
109    /// assert!(vars.cli_arg("key1").is_ok());
110    /// assert!(vars.cli_arg("not-exists").is_err());
111    /// ```
112    pub fn cli_arg(&self, key: &str) -> Result<&str> {
113        self.cli
114            .get(key)
115            .map(String::as_str)
116            .ok_or(Error::Message(format!("the argument {key} does not exist")))
117    }
118}
119
120/// Information about a task, including its name and details.
121#[allow(clippy::module_name_repetitions)]
122#[derive(Debug)]
123pub struct TaskInfo {
124    pub name: String,
125    pub detail: String,
126}
127
128/// A trait defining the behavior of a task.
129#[async_trait]
130pub trait Task: Send + Sync {
131    /// Get information about the task.
132    fn task(&self) -> TaskInfo;
133    /// Execute the task with the provided application context and variables.
134    async fn run(&self, app_context: &AppContext, vars: &Vars) -> Result<()>;
135}
136
137/// Managing and running tasks.
138#[derive(Default)]
139pub struct Tasks {
140    registry: BTreeMap<String, Box<dyn Task>>,
141}
142
143impl Tasks {
144    /// List all registered tasks with their information.
145    #[must_use]
146    pub fn list(&self) -> Vec<TaskInfo> {
147        self.registry.values().map(|t| t.task()).collect::<Vec<_>>()
148    }
149
150    /// List of all tasks names
151    #[must_use]
152    pub fn names(&self) -> Vec<String> {
153        self.registry
154            .values()
155            .map(|t| t.task().name)
156            .collect::<Vec<_>>()
157    }
158
159    /// Run a registered task by name with provided variables.
160    ///
161    /// # Errors
162    ///
163    /// Returns a [`Result`] if an task finished with error. mostly if the given
164    /// task is not found or an error to run the task.s
165    pub async fn run(&self, app_context: &AppContext, task: &str, vars: &Vars) -> Result<()> {
166        let task = self
167            .registry
168            .get(task)
169            .ok_or_else(|| Error::TaskNotFound(task.to_string()))?;
170        task.run(app_context, vars).await?;
171        Ok(())
172    }
173
174    /// Register a new task to the registry.
175    pub fn register(&mut self, task: impl Task + 'static) {
176        let name = task.task().name;
177        self.registry.insert(name, Box::new(task));
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184    use crate::tests_cfg;
185
186    #[tokio::test]
187    async fn test_vars_from_cli_args() {
188        let args = vec![
189            ("key1".to_string(), "value1".to_string()),
190            ("key2".to_string(), "value2".to_string()),
191        ];
192        let vars = Vars::from_cli_args(args);
193
194        assert_eq!(vars.cli.len(), 2);
195        assert_eq!(vars.cli.get("key1"), Some(&"value1".to_string()));
196        assert_eq!(vars.cli.get("key2"), Some(&"value2".to_string()));
197    }
198
199    #[test]
200    fn from_args_is_lenient_and_keeps_everything() {
201        let vars = Vars::from_args(
202            ["a.txt", "--force", "k:v", "url:http://x:80", ":x"]
203                .map(String::from)
204                .to_vec(),
205        );
206        assert_eq!(vars.args().len(), 5);
207        assert_eq!(vars.args()[1], "--force");
208        assert_eq!(vars.cli.len(), 2);
209        assert_eq!(vars.cli_arg("k").unwrap(), "v");
210        assert_eq!(vars.cli_arg("url").unwrap(), "http://x:80");
211        assert!(vars.cli_arg("a.txt").is_err());
212    }
213
214    #[test]
215    fn from_cli_args_populates_args() {
216        let vars = Vars::from_cli_args(vec![("k".into(), "v".into())]);
217        assert_eq!(vars.args(), ["k:v"]);
218    }
219
220    #[tokio::test]
221    async fn test_vars_cli_arg() {
222        let args = vec![("key1".to_string(), "value1".to_string())];
223        let vars = Vars::from_cli_args(args);
224
225        assert_eq!(vars.cli_arg("key1").unwrap(), "value1");
226        assert!(vars.cli_arg("not-exists").is_err());
227    }
228
229    #[tokio::test]
230    async fn test_tasks_registry() {
231        let mut tasks = Tasks::default();
232        tasks.register(tests_cfg::task::Foo);
233        tasks.register(tests_cfg::task::ParseArgs);
234
235        assert_eq!(tasks.names().len(), 2);
236        assert!(tasks.names().contains(&"foo".to_string()));
237        assert!(tasks.names().contains(&"parse_args".to_string()));
238    }
239
240    #[tokio::test]
241    async fn test_tasks_list() {
242        let mut tasks = Tasks::default();
243        tasks.register(tests_cfg::task::Foo);
244        tasks.register(tests_cfg::task::ParseArgs);
245
246        let task_infos = tasks.list();
247        assert_eq!(task_infos.len(), 2);
248
249        let names: Vec<String> = task_infos.iter().map(|info| info.name.clone()).collect();
250        let details: Vec<String> = task_infos.iter().map(|info| info.detail.clone()).collect();
251
252        assert!(names.contains(&"foo".to_string()));
253        assert!(names.contains(&"parse_args".to_string()));
254        assert!(details.contains(&"run foo task".to_string()));
255        assert!(details.contains(&"Validate the paring args".to_string()));
256    }
257
258    #[tokio::test]
259    async fn test_tasks_run_success() {
260        let mut tasks = Tasks::default();
261        tasks.register(tests_cfg::task::Foo);
262
263        let app_context = tests_cfg::app::get_app_context().await;
264        let vars = Vars::default();
265
266        let result = tasks.run(&app_context, "foo", &vars).await;
267        assert!(result.is_ok());
268    }
269
270    #[tokio::test]
271    async fn test_tasks_run_failure() {
272        let mut tasks = Tasks::default();
273        tasks.register(tests_cfg::task::ParseArgs);
274
275        let app_context = tests_cfg::app::get_app_context().await;
276        let vars = Vars::default();
277
278        // ParseArgs will fail with "invalid args" if app != "loco" or refresh != true
279        let result = tasks.run(&app_context, "parse_args", &vars).await;
280        assert!(result.is_err());
281
282        if let Err(Error::Message(msg)) = result {
283            assert_eq!(msg, "invalid args");
284        } else {
285            panic!("Expected Error::Message variant");
286        }
287    }
288
289    #[tokio::test]
290    async fn test_tasks_run_with_args() {
291        let mut tasks = Tasks::default();
292        tasks.register(tests_cfg::task::ParseArgs);
293
294        let app_context = tests_cfg::app::get_app_context().await;
295        let args = vec![
296            ("test".to_string(), "true".to_string()),
297            ("app".to_string(), "loco".to_string()),
298        ];
299        let vars = Vars::from_cli_args(args);
300
301        // ParseArgs will succeed when app == "loco" and test == "true"
302        let result = tasks.run(&app_context, "parse_args", &vars).await;
303        assert!(result.is_ok());
304    }
305
306    #[tokio::test]
307    async fn test_tasks_run_not_found() {
308        let tasks = Tasks::default();
309        let app_context = tests_cfg::app::get_app_context().await;
310        let vars = Vars::default();
311
312        let result = tasks.run(&app_context, "non_existent_task", &vars).await;
313        assert!(result.is_err());
314
315        match result {
316            Err(Error::TaskNotFound(task_name)) => {
317                assert_eq!(task_name, "non_existent_task");
318            }
319            _ => panic!("Expected Error::TaskNotFound variant"),
320        }
321    }
322
323    #[tokio::test]
324    async fn test_task_registration_and_override() {
325        // Create a custom task that will override Foo
326        struct CustomFoo;
327
328        #[async_trait]
329        impl Task for CustomFoo {
330            fn task(&self) -> TaskInfo {
331                TaskInfo {
332                    name: "foo".to_string(),
333                    detail: "Updated foo task".to_string(),
334                }
335            }
336
337            async fn run(&self, _app_context: &AppContext, _vars: &Vars) -> Result<()> {
338                Ok(())
339            }
340        }
341
342        let mut tasks = Tasks::default();
343        tasks.register(tests_cfg::task::Foo);
344        assert_eq!(tasks.names().len(), 1);
345
346        // Register a new task with the same name
347        tasks.register(CustomFoo);
348
349        // Should still have only one task (overwritten)
350        assert_eq!(tasks.names().len(), 1);
351
352        let task_infos = tasks.list();
353        assert_eq!(task_infos[0].detail, "Updated foo task");
354    }
355}