larust_console/lib.rs
1//! Named CLI commands - Laravel's `Artisan::command('name', $closure)`,
2//! as a real trait rather than a closure, matching this codebase's own
3//! established shape for anything dispatched by a stable string tag
4//! (`larust_queue::Job::JOB_TYPE`, `larust_notifications::Notification::
5//! NOTIFICATION_TYPE`) rather than introducing a different shape just for
6//! this one case.
7//!
8//! Deliberately **not** built on `larust_queue::JobRegistry`'s exact
9//! mechanics, even though the shape looks similar at a glance: a `Job` is
10//! serialized, persisted, and reconstructed by a worker process that may
11//! not be the one that dispatched it - `JobRegistry::register::<J>()`'s
12//! closure exists specifically to defer *deserializing* `J` until a
13//! worker actually claims one. A `Command` runs synchronously, in the
14//! same process, the moment its name is typed - there's nothing to
15//! persist or deserialize, so `register` takes no `Default`/`Deserialize`
16//! bound at all, and `Command::handle` is an associated function (no
17//! `&self`) rather than an instance method, since a command has no
18//! meaningful state of its own beyond the `args` it's handed - the same
19//! reasoning `Authenticatable::find_for_auth` being a bare associated
20//! function already established for this codebase.
21//!
22//! # Example
23//!
24//! ```
25//! use larust_console::{Command, CommandRegistry};
26//! use larust_core::AppError;
27//!
28//! struct ReportPosts;
29//!
30//! impl Command for ReportPosts {
31//! const NAME: &'static str = "report:posts";
32//! const DESCRIPTION: &'static str = "Prints the current post count";
33//!
34//! async fn handle(_args: &[String]) -> Result<(), AppError> {
35//! println!("42 posts");
36//! Ok(())
37//! }
38//! }
39//!
40//! # async fn example() -> Result<(), AppError> {
41//! let registry = CommandRegistry::new().register::<ReportPosts>();
42//! let ran = registry.dispatch("report:posts", &[]).await?;
43//! assert!(ran);
44//! # Ok(())
45//! # }
46//! ```
47
48use larust_core::AppError;
49use std::collections::HashMap;
50use std::future::Future;
51use std::pin::Pin;
52
53/// A named CLI command, run once, synchronously, in the same process that
54/// dispatched it - see this crate's own module doc for the full
55/// comparison against `larust_queue::Job`.
56pub trait Command: Send + Sync + 'static {
57 /// The name typed after `xr` to run this command, e.g. `xr
58 /// report:posts` names a command whose `NAME` is `"report:posts"`.
59 /// Colon-namespaced by convention (Laravel's own `make:model`,
60 /// `queue:work`), never enforced - any string works.
61 const NAME: &'static str;
62
63 /// A one-line description, shown by `xr command:list`. Optional -
64 /// defaults to empty rather than requiring every command to supply
65 /// one, since a name alone is often self-explanatory.
66 const DESCRIPTION: &'static str = "";
67
68 /// Runs the command. `args` is every token after the command's own
69 /// name (`xr report:posts --format=json` hands `["--format=json"]`) -
70 /// parsing them is the command's own job, the same "no
71 /// framework-imposed argument-parsing DSL" stance `Job`/`Notification`
72 /// already take for their own payloads.
73 fn handle(args: &[String]) -> impl Future<Output = Result<(), AppError>> + Send;
74}
75
76type BoxedHandler = Box<
77 dyn Fn(Vec<String>) -> Pin<Box<dyn Future<Output = Result<(), AppError>> + Send>> + Send + Sync,
78>;
79
80/// A registered command's name and description, as returned by
81/// [`CommandRegistry::list`] - e.g. for `xr command:list` to print.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct CommandInfo {
84 pub name: &'static str,
85 pub description: &'static str,
86}
87
88/// Maps a command name to the handler that runs it - built fresh by
89/// whatever calls [`CommandRegistry::dispatch`] (typically the generated
90/// app's own `main.rs`, via `routes::console::commands()`), not a
91/// process-wide static: exactly one process ever reads it, for exactly
92/// as long as that one `xr <command>` invocation runs, so there's no
93/// cross-request sharing need the way `larust-events`' listener registry
94/// or `larust_http::route`'s named-route registry have.
95#[must_use]
96#[derive(Default)]
97pub struct CommandRegistry {
98 commands: HashMap<&'static str, (CommandInfo, BoxedHandler)>,
99}
100
101impl CommandRegistry {
102 pub fn new() -> Self {
103 Self::default()
104 }
105
106 /// Registers `C` under its own `Command::NAME`. Panics on a duplicate
107 /// name - a startup-time registration collision is a real programmer
108 /// bug (the shadowed command would silently never run again); failing
109 /// loudly and immediately here beats a confusing "why did `xr
110 /// report:posts` just run the wrong thing" bug report later, the same
111 /// reasoning `JobRegistry::register`'s own duplicate check already
112 /// established for this codebase.
113 pub fn register<C: Command>(mut self) -> Self {
114 let handler: BoxedHandler =
115 Box::new(|args: Vec<String>| Box::pin(async move { C::handle(&args).await }));
116 let info = CommandInfo {
117 name: C::NAME,
118 description: C::DESCRIPTION,
119 };
120 let existing = self.commands.insert(C::NAME, (info, handler));
121 assert!(
122 existing.is_none(),
123 "duplicate CommandRegistry::register for NAME {:?} - each command name must be \
124 registered exactly once",
125 C::NAME,
126 );
127 self
128 }
129
130 /// Runs the named command with `args`, returning `Ok(true)` if a
131 /// command with that name was actually registered and run, or
132 /// `Ok(false)` if nothing matched. `false`, not an error - the
133 /// distinction lets a caller (`main.rs`'s own dispatch chain) fall
134 /// through to its own "unknown command" handling for a name that
135 /// matches neither a registered `Command` nor one of the framework's
136 /// own fixed subcommands (`migrate`, `queue:work`, ...), rather than
137 /// this crate having to know about those at all.
138 pub async fn dispatch(&self, name: &str, args: &[String]) -> Result<bool, AppError> {
139 match self.commands.get(name) {
140 Some((_, handler)) => {
141 handler(args.to_vec()).await?;
142 Ok(true)
143 }
144 None => Ok(false),
145 }
146 }
147
148 /// Every registered command's name and description, sorted by name -
149 /// for `xr command:list` to print in a stable, predictable order
150 /// rather than `HashMap`'s own unspecified iteration order.
151 pub fn list(&self) -> Vec<CommandInfo> {
152 let mut commands: Vec<CommandInfo> =
153 self.commands.values().map(|(info, _)| *info).collect();
154 commands.sort_by_key(|info| info.name);
155 commands
156 }
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162 use std::sync::atomic::{AtomicUsize, Ordering};
163
164 struct Ping;
165 impl Command for Ping {
166 const NAME: &'static str = "ping";
167 const DESCRIPTION: &'static str = "Replies pong";
168
169 async fn handle(_args: &[String]) -> Result<(), AppError> {
170 Ok(())
171 }
172 }
173
174 static CALLS: AtomicUsize = AtomicUsize::new(0);
175 static LAST_ARGS: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
176
177 struct Echo;
178 impl Command for Echo {
179 const NAME: &'static str = "echo";
180
181 async fn handle(args: &[String]) -> Result<(), AppError> {
182 CALLS.fetch_add(1, Ordering::SeqCst);
183 *LAST_ARGS.lock().unwrap() = args.to_vec();
184 Ok(())
185 }
186 }
187
188 struct Failing;
189 impl Command for Failing {
190 const NAME: &'static str = "failing";
191
192 async fn handle(_args: &[String]) -> Result<(), AppError> {
193 Err(AppError::Internal(Box::new(std::io::Error::other(
194 "deliberately failing",
195 ))))
196 }
197 }
198
199 #[tokio::test]
200 async fn dispatch_runs_the_matching_registered_command() {
201 let registry = CommandRegistry::new().register::<Ping>();
202 let ran = registry.dispatch("ping", &[]).await.unwrap();
203 assert!(ran);
204 }
205
206 #[tokio::test]
207 async fn dispatch_forwards_args_to_the_command() {
208 CALLS.store(0, Ordering::SeqCst);
209 let registry = CommandRegistry::new().register::<Echo>();
210 let args = vec!["--dry-run".to_string(), "42".to_string()];
211 registry.dispatch("echo", &args).await.unwrap();
212 assert_eq!(CALLS.load(Ordering::SeqCst), 1);
213 assert_eq!(*LAST_ARGS.lock().unwrap(), args);
214 }
215
216 #[tokio::test]
217 async fn dispatch_returns_false_for_an_unregistered_name() {
218 let registry = CommandRegistry::new().register::<Ping>();
219 let ran = registry.dispatch("not:registered", &[]).await.unwrap();
220 assert!(!ran);
221 }
222
223 #[tokio::test]
224 async fn dispatch_propagates_the_commands_own_error() {
225 let registry = CommandRegistry::new().register::<Failing>();
226 let result = registry.dispatch("failing", &[]).await;
227 assert!(result.is_err());
228 }
229
230 #[test]
231 #[should_panic(expected = "duplicate CommandRegistry::register for NAME \"ping\"")]
232 fn register_panics_on_a_duplicate_name() {
233 struct AlsoPing;
234 impl Command for AlsoPing {
235 const NAME: &'static str = "ping";
236 async fn handle(_args: &[String]) -> Result<(), AppError> {
237 Ok(())
238 }
239 }
240
241 let _ = CommandRegistry::new()
242 .register::<Ping>()
243 .register::<AlsoPing>();
244 }
245
246 #[test]
247 fn list_is_sorted_by_name_regardless_of_registration_order() {
248 struct Zebra;
249 impl Command for Zebra {
250 const NAME: &'static str = "zebra";
251 async fn handle(_args: &[String]) -> Result<(), AppError> {
252 Ok(())
253 }
254 }
255 struct Apple;
256 impl Command for Apple {
257 const NAME: &'static str = "apple";
258 async fn handle(_args: &[String]) -> Result<(), AppError> {
259 Ok(())
260 }
261 }
262
263 let registry = CommandRegistry::new()
264 .register::<Zebra>()
265 .register::<Apple>();
266 let names: Vec<&str> = registry.list().iter().map(|info| info.name).collect();
267 assert_eq!(names, vec!["apple", "zebra"]);
268 }
269
270 #[test]
271 fn list_includes_each_commands_description() {
272 let registry = CommandRegistry::new().register::<Ping>();
273 let list = registry.list();
274 assert_eq!(list.len(), 1);
275 assert_eq!(list[0].name, "ping");
276 assert_eq!(list[0].description, "Replies pong");
277 }
278}