Skip to main content

phoenix_console/
lib.rs

1//! Application console: `myapp update` with a one-function command.
2//! See `docs/QUEUE_MAIL_CONSOLE.md`.
3
4#![forbid(unsafe_code)]
5
6use std::{
7    error::Error,
8    fmt::{Display, Formatter},
9    future::Future,
10    path::{Path, PathBuf},
11    pin::Pin,
12};
13
14/// Result type returned by console commands and [`Console::run`].
15pub type CommandResult = Result<(), Box<dyn Error + Send + Sync>>;
16
17/// Borrowed arguments for a single console invocation.
18#[derive(Clone, Copy, Debug)]
19pub struct CommandContext<'a> {
20    /// Remaining argv after the binary name and command name.
21    pub args: &'a [String],
22    /// Application binary name used in help text.
23    pub binary_name: &'a str,
24}
25
26type BoxedCommandFuture<'a> = Pin<Box<dyn Future<Output = CommandResult> + Send + 'a>>;
27type CommandHandler =
28    Box<dyn for<'a> Fn(CommandContext<'a>) -> BoxedCommandFuture<'a> + Send + Sync>;
29
30/// One registered application command.
31pub struct CommandEntry {
32    name: &'static str,
33    handler: CommandHandler,
34}
35
36impl CommandEntry {
37    /// Wrap an async command function for registration.
38    #[must_use]
39    pub fn new<F>(name: &'static str, handler: F) -> Self
40    where
41        F: for<'a> Fn(CommandContext<'a>) -> BoxedCommandFuture<'a> + Send + Sync + 'static,
42    {
43        Self {
44            name,
45            handler: Box::new(handler),
46        }
47    }
48
49    #[must_use]
50    pub const fn name(&self) -> &'static str {
51        self.name
52    }
53}
54
55/// Application CLI console built around a binary name and named commands.
56pub struct Console {
57    binary_name: String,
58    about: Option<String>,
59    serve: Option<CommandHandler>,
60    commands: Vec<CommandEntry>,
61}
62
63impl Console {
64    /// Create a console whose help text uses `binary_name`.
65    #[must_use]
66    pub fn new(binary_name: impl Into<String>) -> Self {
67        Self {
68            binary_name: binary_name.into(),
69            about: None,
70            serve: None,
71            commands: Vec::new(),
72        }
73    }
74
75    /// Short description printed above the usage block.
76    #[must_use]
77    pub fn about(mut self, about: impl Into<String>) -> Self {
78        self.about = Some(about.into());
79        self
80    }
81
82    /// Register the built-in `serve` command that starts the HTTP application.
83    #[must_use]
84    pub fn serve<F, Fut>(mut self, handler: F) -> Self
85    where
86        F: Fn(CommandContext<'_>) -> Fut + Send + Sync + 'static,
87        Fut: Future<Output = CommandResult> + Send + 'static,
88    {
89        self.serve = Some(Box::new(move |ctx| {
90            let args = ctx.args.to_vec();
91            let binary_name = ctx.binary_name.to_owned();
92            let future = handler(CommandContext {
93                args: &args,
94                binary_name: &binary_name,
95            });
96            Box::pin(future)
97        }));
98        self
99    }
100
101    /// Append user-registered commands from [`commands!`] or a manual list.
102    #[must_use]
103    pub fn commands(mut self, commands: impl IntoIterator<Item = CommandEntry>) -> Self {
104        self.commands.extend(commands);
105        self
106    }
107
108    /// Parse process argv and dispatch.
109    ///
110    /// # Errors
111    ///
112    /// Returns an error when a packaged release root cannot be entered, for
113    /// unknown commands, or when a command fails.
114    pub async fn run(self) -> CommandResult {
115        enter_packaged_release_root()?;
116        self.run_argv(std::env::args()).await
117    }
118
119    /// Parse an explicit argv (including argv0) and dispatch.
120    ///
121    /// # Errors
122    ///
123    /// Returns an error for unknown commands or when a command fails.
124    pub async fn run_argv(
125        self,
126        argv: impl IntoIterator<Item = impl Into<String>>,
127    ) -> CommandResult {
128        let argv = argv.into_iter().map(Into::into).collect::<Vec<_>>();
129        let binary_name = self.binary_name.as_str();
130        let command = argv.get(1).map(String::as_str);
131
132        match command {
133            None | Some("help" | "--help" | "-h") => {
134                print!("{}", self.usage());
135                Ok(())
136            }
137            Some("serve") => {
138                let Some(serve) = &self.serve else {
139                    return Err(Box::new(ConsoleError::ServeUnavailable));
140                };
141                let ctx = CommandContext {
142                    args: argv.get(2..).unwrap_or(&[]),
143                    binary_name,
144                };
145                serve(ctx).await
146            }
147            Some(name) => {
148                let ctx = CommandContext {
149                    args: argv.get(2..).unwrap_or(&[]),
150                    binary_name,
151                };
152                let Some(entry) = self.commands.iter().find(|entry| entry.name == name) else {
153                    return Err(Box::new(ConsoleError::UnknownCommand {
154                        command: name.to_owned(),
155                        usage: self.usage(),
156                    }));
157                };
158                (entry.handler)(ctx).await
159            }
160        }
161    }
162
163    fn usage(&self) -> String {
164        let mut lines = Vec::new();
165        if let Some(about) = &self.about {
166            lines.push(about.clone());
167            lines.push(String::new());
168        }
169        lines.push(format!(
170            "Usage:\n  {} <command> [args...]\n",
171            self.binary_name
172        ));
173        lines.push("Commands:".to_owned());
174        if self.serve.is_some() {
175            lines.push("  serve    Start the HTTP server".to_owned());
176        }
177        let mut names = self
178            .commands
179            .iter()
180            .map(CommandEntry::name)
181            .collect::<Vec<_>>();
182        names.sort_unstable();
183        for name in names {
184            lines.push(format!("  {name}"));
185        }
186        lines.push(String::new());
187        lines.push(format!("Run `{} help` for this message.", self.binary_name));
188        lines.push(String::new());
189        lines.join("\n")
190    }
191}
192
193/// Enter the release root when the executable lives in the conventional
194/// `<release>/bin/<application>` layout.
195///
196/// Phoenix application configuration, static assets, and the Node renderer all
197/// use paths relative to the application root. Process managers normally set
198/// their working directory to `<deploy>/current`, but a release binary should
199/// behave the same when it is started directly from its `bin/` directory.
200fn enter_packaged_release_root() -> std::io::Result<Option<PathBuf>> {
201    let Ok(executable) = std::env::current_exe() else {
202        return Ok(None);
203    };
204    let Some(root) = packaged_release_root(&executable) else {
205        return Ok(None);
206    };
207    std::env::set_current_dir(&root)?;
208    Ok(Some(root))
209}
210
211fn packaged_release_root(executable: &Path) -> Option<PathBuf> {
212    let bin = executable.parent()?;
213    if bin.file_name().and_then(|name| name.to_str()) != Some("bin") {
214        return None;
215    }
216    let root = bin.parent()?;
217    if root.join("manifest.toml").is_file()
218        && root.join("config").is_dir()
219        && root.join("public").is_dir()
220    {
221        Some(root.to_path_buf())
222    } else {
223        None
224    }
225}
226
227enum ConsoleError {
228    UnknownCommand { command: String, usage: String },
229    ServeUnavailable,
230}
231
232impl Display for ConsoleError {
233    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
234        match self {
235            Self::UnknownCommand { command, usage } => {
236                write!(formatter, "unknown command `{command}`\n\n{usage}")
237            }
238            Self::ServeUnavailable => {
239                write!(
240                    formatter,
241                    "command `serve` is not configured; call Console::serve first"
242                )
243            }
244        }
245    }
246}
247
248impl std::fmt::Debug for ConsoleError {
249    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
250        Display::fmt(self, formatter)
251    }
252}
253
254impl Error for ConsoleError {}
255/// Register application commands without clap boilerplate.
256///
257/// # Examples
258///
259/// ```ignore
260/// commands! {
261///     update,
262///     "sync-users" => sync_users,
263/// }
264/// ```
265///
266/// Generates `pub fn registry() -> Vec<CommandEntry>` in the enclosing module.
267#[macro_export]
268macro_rules! commands {
269    (@push $entries:ident;) => {};
270    (@push $entries:ident; $name:ident) => {
271        $entries.push($crate::CommandEntry::new(
272            stringify!($name),
273            |__ctx| ::std::boxed::Box::pin($name(__ctx)),
274        ));
275    };
276    (@push $entries:ident; $name:ident,) => {
277        $crate::commands!(@push $entries; $name);
278    };
279    (@push $entries:ident; $name:ident, $($rest:tt)*) => {
280        $crate::commands!(@push $entries; $name);
281        $crate::commands!(@push $entries; $($rest)*);
282    };
283    (@push $entries:ident; $alias:literal => $handler:ident) => {
284        $entries.push($crate::CommandEntry::new(
285            $alias,
286            |__ctx| ::std::boxed::Box::pin($handler(__ctx)),
287        ));
288    };
289    (@push $entries:ident; $alias:literal => $handler:ident,) => {
290        $crate::commands!(@push $entries; $alias => $handler);
291    };
292    (@push $entries:ident; $alias:literal => $handler:ident, $($rest:tt)*) => {
293        $crate::commands!(@push $entries; $alias => $handler);
294        $crate::commands!(@push $entries; $($rest)*);
295    };
296    () => {
297        /// Registered application console commands.
298        #[must_use]
299        pub fn registry() -> Vec<$crate::CommandEntry> {
300            Vec::new()
301        }
302    };
303    ($($item:tt)*) => {
304        /// Registered application console commands.
305        #[must_use]
306        #[allow(clippy::vec_init_then_push)]
307        pub fn registry() -> Vec<$crate::CommandEntry> {
308            let mut __phoenix_commands = Vec::new();
309            $crate::commands!(@push __phoenix_commands; $($item)*);
310            __phoenix_commands
311        }
312    };
313}
314
315#[must_use]
316pub const fn crate_name() -> &'static str {
317    "phoenix-console"
318}
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323    use std::fs;
324    use std::sync::{
325        Arc,
326        atomic::{AtomicBool, Ordering},
327    };
328    use std::time::{SystemTime, UNIX_EPOCH};
329
330    #[allow(clippy::unused_async)]
331    async fn update(_ctx: CommandContext<'_>) -> CommandResult {
332        Ok(())
333    }
334
335    commands! {
336        update,
337    }
338
339    #[tokio::test]
340    async fn registered_update_command_runs() {
341        let result = Console::new("demo")
342            .about("Demo")
343            .commands(registry())
344            .run_argv(["demo", "update"])
345            .await;
346        assert!(result.is_ok());
347    }
348
349    #[tokio::test]
350    async fn unknown_command_fails() {
351        let result = Console::new("demo")
352            .commands(registry())
353            .run_argv(["demo", "nope"])
354            .await;
355        let error = result.expect_err("unknown command should fail");
356        assert!(error.to_string().contains("unknown command `nope`"));
357    }
358
359    #[tokio::test]
360    async fn help_does_not_panic() {
361        Console::new("demo")
362            .about("Demo app")
363            .serve(|_ctx| async move { Ok(()) })
364            .commands(registry())
365            .run_argv(["demo", "help"])
366            .await
367            .expect("help should succeed");
368        Console::new("demo")
369            .run_argv(["demo"])
370            .await
371            .expect("empty argv should print usage");
372    }
373
374    #[tokio::test]
375    async fn serve_invokes_handler() {
376        let called = Arc::new(AtomicBool::new(false));
377        let flag = Arc::clone(&called);
378        Console::new("demo")
379            .serve(move |_ctx| {
380                let flag = Arc::clone(&flag);
381                async move {
382                    flag.store(true, Ordering::SeqCst);
383                    Ok(())
384                }
385            })
386            .run_argv(["demo", "serve"])
387            .await
388            .expect("serve should succeed");
389        assert!(called.load(Ordering::SeqCst));
390    }
391
392    #[test]
393    fn discovers_packaged_release_root_from_bin_executable() {
394        let root = temporary_directory("packaged-root");
395        fs::create_dir_all(root.join("bin")).unwrap();
396        fs::create_dir_all(root.join("config")).unwrap();
397        fs::create_dir_all(root.join("public")).unwrap();
398        fs::write(root.join("manifest.toml"), "schema_version = 1\n").unwrap();
399
400        assert_eq!(
401            packaged_release_root(&root.join("bin/demo")),
402            Some(root.clone())
403        );
404        assert_eq!(packaged_release_root(&root.join("demo")), None);
405
406        fs::remove_dir_all(root).unwrap();
407    }
408
409    #[test]
410    fn ignores_incomplete_bin_layouts() {
411        let root = temporary_directory("incomplete-root");
412        fs::create_dir_all(root.join("bin")).unwrap();
413        fs::create_dir_all(root.join("config")).unwrap();
414        fs::create_dir_all(root.join("public")).unwrap();
415
416        assert_eq!(packaged_release_root(&root.join("bin/demo")), None);
417
418        fs::remove_dir_all(root).unwrap();
419    }
420
421    fn temporary_directory(label: &str) -> PathBuf {
422        let nonce = SystemTime::now()
423            .duration_since(UNIX_EPOCH)
424            .unwrap()
425            .as_nanos();
426        std::env::temp_dir().join(format!(
427            "phoenix-console-{label}-{}-{nonce}",
428            std::process::id()
429        ))
430    }
431
432    #[tokio::test]
433    async fn command_receives_remaining_args() {
434        #[allow(clippy::unused_async)]
435        async fn echo(ctx: CommandContext<'_>) -> CommandResult {
436            assert_eq!(ctx.binary_name, "demo");
437            assert_eq!(ctx.args, ["a".to_owned(), "b".to_owned()]);
438            Ok(())
439        }
440
441        let entry = CommandEntry::new("echo", |ctx| Box::pin(echo(ctx)));
442        Console::new("demo")
443            .commands([entry])
444            .run_argv(["demo", "echo", "a", "b"])
445            .await
446            .expect("echo should succeed");
447    }
448}