glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! App tasks: code run from the command line, as Rails' rake tasks and
//! Laravel's commands. In `.glacier`, `src/tasks.glacier` holds them:
//!
//! ```text
//! # Sends one user's weekly report.
//! task "reports:send", user_id: i64 do
//!   Reports.send_to(User.find(user_id)!)!
//! end
//! ```
//!
//! `glacier run reports:send 12` runs it in development, and the app
//! binary `app reports:send 12` in production; `app tasks` lists them.
//! A task runs with the app's databases, outside any request.

use std::future::Future;
use std::pin::Pin;
use std::str::FromStr;

use crate::error::{Error, Result};

/// Prints a line to standard output, as Ruby's `puts`: what a task
/// tells whoever ran it (`puts("Expired #{n} reports.")`).
pub fn puts(text: impl std::fmt::Display) {
    println!("{text}");
}

/// What a task's body returns.
pub type Run = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// A task: its name, what it does, its arguments and its body.
#[derive(Clone)]
pub struct Task {
    pub name: &'static str,
    /// The comment above it, for `app tasks`.
    pub about: &'static str,
    /// Its arguments, in order, as `user_id: i64`.
    pub args: &'static [&'static str],
    pub run: fn(Vec<String>) -> Run,
}

impl Task {
    /// `reports:send user_id: i64`, as `app tasks` lists it.
    pub fn usage(&self) -> String {
        let mut usage = self.name.to_owned();
        for arg in self.args {
            // `days: Option<i64>` → `[days: i64]`.
            match arg.split_once(": Option<") {
                Some((name, ty)) => {
                    usage.push_str(&format!(
                        " [{name}: {}]",
                        ty.strip_suffix('>').unwrap_or(ty)
                    ));
                }
                None => usage.push_str(&format!(" <{arg}>")),
            }
        }
        usage
    }
}

/// The task's argument at `index`, parsed: `arg::<i64>(&args, 0,
/// "user_id")`.
///
/// # Errors
///
/// When it's missing or doesn't parse, naming it.
pub fn arg<T: FromStr>(args: &[String], index: usize, name: &str) -> Result<T> {
    let value = given(args, index, name)
        .ok_or_else(|| Error::internal(format!("missing argument `{name}`")))?;
    parse(&value, name)
}

/// An optional argument: `None` when it isn't given.
///
/// # Errors
///
/// When it's given but doesn't parse.
pub fn optional<T: FromStr>(args: &[String], index: usize, name: &str) -> Result<Option<T>> {
    given(args, index, name)
        .map(|value| parse(&value, name))
        .transpose()
}

/// The argument named `name`, given by name (`--report-id 7`,
/// `--report_id=7`) or else in its place among the others.
fn given(args: &[String], index: usize, name: &str) -> Option<String> {
    let flags = [name.to_owned(), name.replace('_', "-")];
    let mut positional = Vec::new();
    let mut found = None;
    let mut rest = args.iter();
    while let Some(arg) = rest.next() {
        match arg.strip_prefix("--") {
            Some(flag) => {
                let (flag, value) = match flag.split_once('=') {
                    Some((flag, value)) => (flag, Some(value.to_owned())),
                    None => (flag, rest.next().cloned()),
                };
                if flags.iter().any(|f| f == flag) {
                    found = value;
                }
            }
            None => positional.push(arg.clone()),
        }
    }
    found.or_else(|| positional.get(index).cloned())
}

fn parse<T: FromStr>(value: &str, name: &str) -> Result<T> {
    value.parse().map_err(|_| {
        Error::internal(format!(
            "argument `{name}` should be {}, not `{value}`",
            short_type::<T>()
        ))
    })
}

/// `i64`, not `core::primitive::i64`.
fn short_type<T>() -> &'static str {
    let name = std::any::type_name::<T>();
    name.rsplit("::").next().unwrap_or(name)
}

/// The app's tasks, for [`RunTask`] in a worker: set as the app is
/// built.
static TASKS: std::sync::RwLock<Vec<Task>> = std::sync::RwLock::new(Vec::new());

pub(crate) fn install(tasks: &[Task]) {
    let mut installed = TASKS.write().unwrap_or_else(|e| e.into_inner());
    for task in tasks {
        if !installed.iter().any(|t| t.name == task.name) {
            installed.push(task.clone());
        }
    }
}

/// The job that runs a task on a schedule: `cron "0 3 * * *", task:
/// "reports:expire"` in the app's `jobs do`
/// (`jobs.cron("reports:expire", "0 3 * * *", RunTask::new("reports:expire", [] as [&str; 0]))`
/// in Rust).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RunTask {
    pub task: String,
    pub args: Vec<String>,
}

impl RunTask {
    pub fn new<T: std::fmt::Display>(task: &str, args: impl IntoIterator<Item = T>) -> Self {
        Self {
            task: task.to_owned(),
            args: args.into_iter().map(|a| a.to_string()).collect(),
        }
    }

    /// The schedule's name: the task, and its arguments if any.
    pub fn schedule_name(&self) -> String {
        std::iter::once(self.task.as_str())
            .chain(self.args.iter().map(String::as_str))
            .collect::<Vec<_>>()
            .join(" ")
    }
}

impl crate::jobs::Job for RunTask {
    const NAME: &'static str = "glacier_run_task";

    async fn perform(self) -> Result<()> {
        let task = TASKS
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .iter()
            .find(|t| t.name == self.task)
            .cloned()
            .ok_or_else(|| Error::internal(format!("no task `{}` to run", self.task)))?;
        (task.run)(self.args).await
    }
}

/// The listing `app tasks` prints: each task's usage and what it does.
pub(crate) fn listing(tasks: &[Task]) -> String {
    if tasks.is_empty() {
        return "No tasks. Add them to src/tasks.glacier.\n".to_owned();
    }
    let width = tasks.iter().map(|t| t.usage().len()).max().unwrap_or(0);
    let mut out = String::new();
    for task in tasks {
        let line = format!("{:width$}  {}", task.usage(), task.about);
        out.push_str(line.trim_end());
        out.push('\n');
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn arguments_parse_by_type_and_name_themselves_when_wrong() {
        let args = vec!["12".to_owned(), "x".to_owned()];
        assert_eq!(arg::<i64>(&args, 0, "user_id").unwrap(), 12);
        let wrong = arg::<i64>(&args, 1, "days").unwrap_err();
        assert!(
            wrong
                .to_string()
                .contains("argument `days` should be i64, not `x`"),
            "{wrong}"
        );
        let missing = arg::<i64>(&args, 2, "limit").unwrap_err();
        assert!(
            missing.to_string().contains("missing argument `limit`"),
            "{missing}"
        );
        assert_eq!(optional::<i64>(&args, 2, "limit").unwrap(), None);
        assert_eq!(
            optional::<String>(&args, 1, "name").unwrap(),
            Some("x".to_owned())
        );
    }

    #[test]
    fn arguments_can_be_given_by_name() {
        let args: Vec<String> = ["--days", "10", "7"]
            .iter()
            .map(|a| a.to_string())
            .collect();
        assert_eq!(arg::<i64>(&args, 0, "report_id").unwrap(), 7);
        assert_eq!(optional::<i64>(&args, 1, "days").unwrap(), Some(10));
        let args: Vec<String> = ["--report-id=3"].iter().map(|a| a.to_string()).collect();
        assert_eq!(arg::<i64>(&args, 0, "report_id").unwrap(), 3);
    }

    #[test]
    fn listing_shows_usage_and_about() {
        fn run(_: Vec<String>) -> Run {
            Box::pin(async { Ok(()) })
        }
        let tasks = [
            Task {
                name: "reports:send",
                about: "Sends a report.",
                args: &["user_id: i64"],
                run,
            },
            Task {
                name: "cleanup",
                about: "",
                args: &[],
                run,
            },
            Task {
                name: "expire",
                about: "Expires.",
                args: &["days: Option<i64>"],
                run,
            },
        ];
        assert_eq!(
            listing(&tasks),
            "reports:send <user_id: i64>  Sends a report.\ncleanup\nexpire [days: i64]           Expires.\n"
        );
    }
}