Skip to main content

glacier/
task.rs

1//! App tasks: code run from the command line, as Rails' rake tasks and
2//! Laravel's commands. In `.glacier`, `src/tasks.glacier` holds them:
3//!
4//! ```text
5//! # Sends one user's weekly report.
6//! task "reports:send", user_id: i64 do
7//!   Reports.send_to(User.find(user_id)!)!
8//! end
9//! ```
10//!
11//! `glacier run reports:send 12` runs it in development, and the app
12//! binary `app reports:send 12` in production; `app tasks` lists them.
13//! A task runs with the app's databases, outside any request.
14
15use std::future::Future;
16use std::pin::Pin;
17use std::str::FromStr;
18
19use crate::error::{Error, Result};
20
21/// Prints a line to standard output, as Ruby's `puts`: what a task
22/// tells whoever ran it (`puts("Expired #{n} reports.")`).
23pub fn puts(text: impl std::fmt::Display) {
24    println!("{text}");
25}
26
27/// What a task's body returns.
28pub type Run = Pin<Box<dyn Future<Output = Result<()>> + Send>>;
29
30/// A task: its name, what it does, its arguments and its body.
31#[derive(Clone)]
32pub struct Task {
33    pub name: &'static str,
34    /// The comment above it, for `app tasks`.
35    pub about: &'static str,
36    /// Its arguments, in order, as `user_id: i64`.
37    pub args: &'static [&'static str],
38    pub run: fn(Vec<String>) -> Run,
39}
40
41impl Task {
42    /// `reports:send user_id: i64`, as `app tasks` lists it.
43    pub fn usage(&self) -> String {
44        let mut usage = self.name.to_owned();
45        for arg in self.args {
46            // `days: Option<i64>` → `[days: i64]`.
47            match arg.split_once(": Option<") {
48                Some((name, ty)) => {
49                    usage.push_str(&format!(
50                        " [{name}: {}]",
51                        ty.strip_suffix('>').unwrap_or(ty)
52                    ));
53                }
54                None => usage.push_str(&format!(" <{arg}>")),
55            }
56        }
57        usage
58    }
59}
60
61/// The task's argument at `index`, parsed: `arg::<i64>(&args, 0,
62/// "user_id")`.
63///
64/// # Errors
65///
66/// When it's missing or doesn't parse, naming it.
67pub fn arg<T: FromStr>(args: &[String], index: usize, name: &str) -> Result<T> {
68    let value = given(args, index, name)
69        .ok_or_else(|| Error::internal(format!("missing argument `{name}`")))?;
70    parse(&value, name)
71}
72
73/// An optional argument: `None` when it isn't given.
74///
75/// # Errors
76///
77/// When it's given but doesn't parse.
78pub fn optional<T: FromStr>(args: &[String], index: usize, name: &str) -> Result<Option<T>> {
79    given(args, index, name)
80        .map(|value| parse(&value, name))
81        .transpose()
82}
83
84/// The argument named `name`, given by name (`--report-id 7`,
85/// `--report_id=7`) or else in its place among the others.
86fn given(args: &[String], index: usize, name: &str) -> Option<String> {
87    let flags = [name.to_owned(), name.replace('_', "-")];
88    let mut positional = Vec::new();
89    let mut found = None;
90    let mut rest = args.iter();
91    while let Some(arg) = rest.next() {
92        match arg.strip_prefix("--") {
93            Some(flag) => {
94                let (flag, value) = match flag.split_once('=') {
95                    Some((flag, value)) => (flag, Some(value.to_owned())),
96                    None => (flag, rest.next().cloned()),
97                };
98                if flags.iter().any(|f| f == flag) {
99                    found = value;
100                }
101            }
102            None => positional.push(arg.clone()),
103        }
104    }
105    found.or_else(|| positional.get(index).cloned())
106}
107
108fn parse<T: FromStr>(value: &str, name: &str) -> Result<T> {
109    value.parse().map_err(|_| {
110        Error::internal(format!(
111            "argument `{name}` should be {}, not `{value}`",
112            short_type::<T>()
113        ))
114    })
115}
116
117/// `i64`, not `core::primitive::i64`.
118fn short_type<T>() -> &'static str {
119    let name = std::any::type_name::<T>();
120    name.rsplit("::").next().unwrap_or(name)
121}
122
123/// The app's tasks, for [`RunTask`] in a worker: set as the app is
124/// built.
125static TASKS: std::sync::RwLock<Vec<Task>> = std::sync::RwLock::new(Vec::new());
126
127pub(crate) fn install(tasks: &[Task]) {
128    let mut installed = TASKS.write().unwrap_or_else(|e| e.into_inner());
129    for task in tasks {
130        if !installed.iter().any(|t| t.name == task.name) {
131            installed.push(task.clone());
132        }
133    }
134}
135
136/// The job that runs a task on a schedule: `cron "0 3 * * *", task:
137/// "reports:expire"` in the app's `jobs do`
138/// (`jobs.cron("reports:expire", "0 3 * * *", RunTask::new("reports:expire", [] as [&str; 0]))`
139/// in Rust).
140#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
141pub struct RunTask {
142    pub task: String,
143    pub args: Vec<String>,
144}
145
146impl RunTask {
147    pub fn new<T: std::fmt::Display>(task: &str, args: impl IntoIterator<Item = T>) -> Self {
148        Self {
149            task: task.to_owned(),
150            args: args.into_iter().map(|a| a.to_string()).collect(),
151        }
152    }
153
154    /// The schedule's name: the task, and its arguments if any.
155    pub fn schedule_name(&self) -> String {
156        std::iter::once(self.task.as_str())
157            .chain(self.args.iter().map(String::as_str))
158            .collect::<Vec<_>>()
159            .join(" ")
160    }
161}
162
163impl crate::jobs::Job for RunTask {
164    const NAME: &'static str = "glacier_run_task";
165
166    async fn perform(self) -> Result<()> {
167        let task = TASKS
168            .read()
169            .unwrap_or_else(|e| e.into_inner())
170            .iter()
171            .find(|t| t.name == self.task)
172            .cloned()
173            .ok_or_else(|| Error::internal(format!("no task `{}` to run", self.task)))?;
174        (task.run)(self.args).await
175    }
176}
177
178/// The listing `app tasks` prints: each task's usage and what it does.
179pub(crate) fn listing(tasks: &[Task]) -> String {
180    if tasks.is_empty() {
181        return "No tasks. Add them to src/tasks.glacier.\n".to_owned();
182    }
183    let width = tasks.iter().map(|t| t.usage().len()).max().unwrap_or(0);
184    let mut out = String::new();
185    for task in tasks {
186        let line = format!("{:width$}  {}", task.usage(), task.about);
187        out.push_str(line.trim_end());
188        out.push('\n');
189    }
190    out
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    #[test]
198    fn arguments_parse_by_type_and_name_themselves_when_wrong() {
199        let args = vec!["12".to_owned(), "x".to_owned()];
200        assert_eq!(arg::<i64>(&args, 0, "user_id").unwrap(), 12);
201        let wrong = arg::<i64>(&args, 1, "days").unwrap_err();
202        assert!(
203            wrong
204                .to_string()
205                .contains("argument `days` should be i64, not `x`"),
206            "{wrong}"
207        );
208        let missing = arg::<i64>(&args, 2, "limit").unwrap_err();
209        assert!(
210            missing.to_string().contains("missing argument `limit`"),
211            "{missing}"
212        );
213        assert_eq!(optional::<i64>(&args, 2, "limit").unwrap(), None);
214        assert_eq!(
215            optional::<String>(&args, 1, "name").unwrap(),
216            Some("x".to_owned())
217        );
218    }
219
220    #[test]
221    fn arguments_can_be_given_by_name() {
222        let args: Vec<String> = ["--days", "10", "7"]
223            .iter()
224            .map(|a| a.to_string())
225            .collect();
226        assert_eq!(arg::<i64>(&args, 0, "report_id").unwrap(), 7);
227        assert_eq!(optional::<i64>(&args, 1, "days").unwrap(), Some(10));
228        let args: Vec<String> = ["--report-id=3"].iter().map(|a| a.to_string()).collect();
229        assert_eq!(arg::<i64>(&args, 0, "report_id").unwrap(), 3);
230    }
231
232    #[test]
233    fn listing_shows_usage_and_about() {
234        fn run(_: Vec<String>) -> Run {
235            Box::pin(async { Ok(()) })
236        }
237        let tasks = [
238            Task {
239                name: "reports:send",
240                about: "Sends a report.",
241                args: &["user_id: i64"],
242                run,
243            },
244            Task {
245                name: "cleanup",
246                about: "",
247                args: &[],
248                run,
249            },
250            Task {
251                name: "expire",
252                about: "Expires.",
253                args: &["days: Option<i64>"],
254                run,
255            },
256        ];
257        assert_eq!(
258            listing(&tasks),
259            "reports:send <user_id: i64>  Sends a report.\ncleanup\nexpire [days: i64]           Expires.\n"
260        );
261    }
262}