rumtk_core/cli.rs
1/*
2 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 * This toolkit aims to be reliable, simple, performant, and standards compliant.
4 * Copyright (C) 2025 Luis M. Santos, M.D. <lsantos@medicalmasses.com>
5 * Copyright (C) 2025 MedicalMasses L.L.C. <contact@medicalmasses.com>
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21///
22/// Tools for handling reading and writing from the standard I/O/E.
23///
24/// Per this [stackoverflow discussion](https://unix.stackexchange.com/questions/37508/in-what-order-do-piped-commands-run).
25/// Note:
26///```text
27/// Piped commands run concurrently. When you run ps | grep …, it's the luck of the draw (or a matter of details of the workings of the shell combined with scheduler fine-tuning deep in the bowels of the kernel) as to whether ps or grep starts first, and in any case they continue to execute concurrently.
28///
29/// This is very commonly used to allow the second program to process data as it comes out from the first program, before the first program has completed its operation. For example
30///
31/// grep pattern very-large-file | tr a-z A-Z
32/// begins to display the matching lines in uppercase even before grep has finished traversing the large file.
33///
34/// grep pattern very-large-file | head -n 1
35/// displays the first matching line, and may stop processing well before grep has finished reading its input file.
36///
37/// If you read somewhere that piped programs run in sequence, flee this document. Piped programs run concurrently and always have.
38/// ```
39///
40/// I bring the note above because that was my original understanding, but I have had to spend a
41/// crazy amount of time trying to get data flowing from one process to another without the initial
42/// process first exiting.
43///
44pub mod cli_utils {
45 use crate::base::{RUMResult, RUMVec};
46 use crate::cpu::CPU_PAGE_SIZE;
47 use crate::strings::{rumtk_format, RUMString};
48 use crate::types::RUMCLIParser;
49 use rumtk_arena::AsRUMSlice;
50 use std::io::{stdin, stdout, BufWriter, Read, Write};
51 #[cfg(any(target_family = "unix", target_os = "linux", target_os = "macos"))]
52 use std::os::fd::{AsRawFd, FromRawFd};
53
54 pub type BufferSlice = RUMVec<u8>;
55 pub type CliSTDInput = RUMVec<u8>;
56 pub type CliSTDOutput<R: AsRUMSlice> = R;
57 pub type BufferChunk = [u8; STD_IN_STEP_SIZE];
58
59 const STD_IN_STEP_SIZE: usize = u16::MAX as usize;
60
61 pub enum CliProcessor<Args> {
62 Direct(fn(args: &Args) -> RUMResult<()>),
63 Message(fn(msg: RUMVec<u8>, args: &Args) -> RUMResult<RUMString>),
64 }
65
66 ///
67 /// Consumes the incoming buffer in chunks of [CPU_PAGE_SIZE](CPU_PAGE_SIZE) bytes size
68 /// until no more bytes are present.
69 ///
70 /// To avoid calling a blocking read, we check if the read yielded an amount of bytes fewer than
71 /// the requested chunk size.
72 ///
73 /// ## Example
74 ///
75 /// ```
76 /// use rumtk_core::cli::cli_utils::{read_stdin};
77 /// use rumtk_core::cpu::CPU_PAGE_SIZE;
78 ///
79 /// let stdin_data = read_stdin(CPU_PAGE_SIZE).unwrap();
80 ///
81 /// assert_eq!(stdin_data.len(), 0, "Returned data with {} size even though we expected 0 bytes!", stdin_data.len())
82 /// ```
83 ///
84 pub fn read_stdin(minimum_size: usize) -> RUMResult<CliSTDInput> {
85 let mut stdin_buffer = CliSTDInput::with_capacity(minimum_size);
86
87 loop {
88 let s = read_some_stdin(&mut stdin_buffer)?;
89
90 // If we attempt the next read, it is likely to be a 0 byte read. Why does this matter?
91 // Well, if the other end of the pipe is still open, the read call will stall in Rust's
92 // std and it is because it expects EOF but that never comes.
93 // If you look at https://man7.org/linux/man-pages/man2/read.2.html, read should return
94 // 0 and simply let us naturally break, but a read < than requested buffer appears to be
95 // an equally valid way to handle terminal and piped data.
96 // We have to check against 0 because the more optimal the buffer size we ask for (e.g.
97 // larger reads for minimum syscall time) the less likely the kernel is ready with the
98 // requested data.
99
100 // Example reads at u16::Max
101 // Read 65535 bytes
102 // Read 61441 bytes
103 // Read 65535 bytes
104 // Read 61441 bytes
105 // Read 8192 bytes
106 // Read 65535 bytes
107 // Read 61441 bytes
108 // Read 65535 bytes
109 // Read 61441 bytes
110 // Read 8192 bytes
111 // Read 65535 bytes
112 // Read 61441 bytes
113 // Read 65535 bytes
114 // Read 61441 bytes
115 // Read 8192 bytes
116 // Read 65535 bytes
117 // Read 61441 bytes
118 // Read 65535 bytes
119 // Read 61441 bytes
120 // Read 8192 bytes
121 // Read 65535 bytes
122 // Read 61441 bytes
123 // Read 65535 bytes
124 // Read 61441 bytes
125 // Read 8192 bytes
126 // Read 65535 bytes
127 // Read 61441 bytes
128 // Read 65535 bytes
129 // Read 61441 bytes
130 // Read 8192 bytes
131 // Read 65535 bytes
132 // Read 61441 bytes
133 // Read 65535 bytes
134 // Read 61441 bytes
135 // Read 8192 bytes
136 // Read 65535 bytes
137 // Read 61441 bytes
138 // Read 65535 bytes
139 // Read 61441 bytes
140 // Read 8192 bytes
141 // Read 65535 bytes
142 // Read 61441 bytes
143 // Read 65535 bytes
144 // Read 41974 bytes
145 // Read 0 bytes
146 // Total: 2331637 => 2.2MB
147 if s == 0 {
148 break;
149 }
150 }
151
152 Ok(stdin_buffer)
153 }
154
155 ///
156 /// Consumes the incoming buffer in chunks of [CPU_SIMD_64_SIZE](crate::cpu::CPU_SIMD_64_SIZE) bytes size.
157 ///
158 /// ## Example
159 ///
160 /// ```
161 /// use std::io::stdin;
162 /// use std::io::prelude::*;
163 /// use std::process::{Command, Stdio};
164 /// use rumtk_core::cli::cli_utils::{read_some_stdin};
165 /// use rumtk_core::cpu::CPU_PAGE_SIZE;
166 /// use rumtk_core::base::RUMVec;
167 ///
168 /// let mut stdin_buffer = RUMVec::with_capacity(CPU_PAGE_SIZE);
169 /// let mut s = read_some_stdin(&mut stdin_buffer).unwrap();
170 /// let mut totas_s = s;
171 /// while s > 0 {
172 /// s = read_some_stdin(&mut stdin_buffer).unwrap();
173 /// totas_s += s;
174 /// }
175 ///
176 /// assert_eq!(totas_s, 0, "Returned data with {} size even though we expected 0 bytes!", totas_s)
177 /// ```
178 ///
179 #[inline]
180 pub fn read_some_stdin(buf: &mut BufferSlice) -> RUMResult<usize> {
181 let mut chunk: BufferChunk = [0; STD_IN_STEP_SIZE];
182
183 match stdin().read(&mut chunk[..]) {
184 Ok(s) => {
185 buf.extend_from_slice(&chunk[..s]);
186 Ok(s)
187 }
188 Err(e) => Err(rumtk_format!("Error reading stdin chunk because {}!", e)),
189 }
190 }
191
192 ///
193 /// Writes [RUMBuffer] to `stdout`.
194 ///
195 #[cfg(target_os = "windows")]
196 pub fn write_stdout<R: AsSlice>(data: CliSTDOutput<R>) -> RUMResult<()> {
197 match stdout().write_all(data.as_rum_slice()) {
198 Ok(_) => {}
199 Err(e) => return Err(rumtk_format!("Error writing to stdout because => {}", e)),
200 };
201 flush_stdout()?;
202 Ok(())
203 }
204
205 #[cfg(any(target_family = "unix", target_os = "linux", target_os = "macos"))]
206 pub fn write_stdout<R: AsRUMSlice>(data: CliSTDOutput<R>) -> RUMResult<()> {
207 // Create an unbuffered File handle from file descriptor 1 (stdout)
208 let stdout_fd = stdout().as_raw_fd();
209
210 {
211 let mut file = BufWriter::new(unsafe { std::fs::File::from_raw_fd(stdout_fd) });
212
213 // Write bytes directly
214 match file.write_all(data.as_rum_slice()) {
215 Ok(_) => {
216 file.flush().unwrap_or_default();
217 std::mem::forget(file);
218 },
219 Err(e) => return Err(rumtk_format!("Error writing to stdout because {}", e)),
220 };
221 }
222
223 flush_stdout()?;
224 Ok(())
225 }
226
227 fn flush_stdout() -> RUMResult<()> {
228 match stdout().flush() {
229 Ok(_) => Ok(()),
230 Err(e) => Err(rumtk_format!("Error flushing stdout because => {}", e)),
231 }
232 }
233
234 pub fn process_message<Args, PF, R>(args: &Args, processor: PF) -> RUMResult<()>
235 where
236 Args: RUMCLIParser,
237 R: AsRUMSlice,
238 PF: Fn(CliSTDInput, &Args) -> RUMResult<R>
239 {
240 let stdin_msg = read_stdin(CPU_PAGE_SIZE * CPU_PAGE_SIZE)?;
241 if !stdin_msg.is_empty() {
242 let out_data = processor(stdin_msg, args)?;
243
244 write_stdout(out_data)?;
245 }
246 Ok(())
247 }
248
249 pub fn process_message_loop<Args, PF>(args: &Args, processor: &PF)
250 where
251 Args: RUMCLIParser,
252 PF: Fn(CliSTDInput, &Args) -> RUMResult<RUMString>
253 {
254 loop {
255 match process_message(args, processor) {
256 Ok(()) => continue,
257 Err(e) => println!("{}", e), // TODO: missing log call
258 };
259 }
260 }
261
262 pub fn print_license_notice(program: &str, year: &str, author_list: &Vec<&str>) {
263 let authors = author_list.join(", ");
264 let notice = rumtk_format!(
265 r" {program} Copyright (C) {year} {authors}
266 This program comes with ABSOLUTELY NO WARRANTY.
267 This is free software, and you are welcome to redistribute it
268 under certain conditions."
269 );
270 eprintln!("{}", notice);
271 }
272}
273
274pub mod macros {
275 ///
276 ///
277 ///
278 #[macro_export]
279 macro_rules! rumtk_cli_define_args {
280 (
281 $(
282 $(#[$field_meta:meta])*
283 $field_name:ident : $field_typ:ty
284 ),* $(,)?
285 ) => {
286 #[derive($crate::types::RUMCLIParser, Debug)]
287 #[command(author, version, about, long_about = None)]
288 pub struct RUMTKInterfaceArgs {
289 $(
290 $(#[$field_meta])*
291 pub $field_name: $field_typ,
292 )*
293 ///
294 /// Specifies command line script to execute on message.
295 ///
296 #[arg(short, long, default_value_t = 1)]
297 pub threads: usize,
298 ///
299 /// Don't write to stdout. Mostly used to distinguish between performance issues with parser
300 /// vs. serde's JSON serialization.
301 ///
302 #[arg(short, long)]
303 pub quiet: bool,
304 ///
305 /// Only used if in client/outbound mode. Places the interface into a loop constantly looking
306 /// for messages in stdin to ship to the connected listening interface.
307 ///
308 #[arg(short, long)]
309 pub daemon: bool,
310 }
311 };
312 }
313
314 ///
315 /// Reads STDIN and unescapes the incoming message.
316 /// Return this unescaped message.
317 ///
318 /// # Example
319 ///
320 /// ## Without specifying the minimum read size.
321 /// ```
322 /// use rumtk_core::base::{RUMResult, RUMVec};
323 /// use rumtk_core::buffers::*;
324 /// use rumtk_core::rumtk_read_stdin;
325 ///
326 /// fn test_read_stdin() -> RUMResult<RUMVec<u8>> {
327 /// rumtk_read_stdin!()
328 /// }
329 ///
330 /// match test_read_stdin() {
331 /// Ok(s) => (),
332 /// Err(e) => panic!("Error reading stdin because => {}", e)
333 /// }
334 /// ```
335 ///
336 /// ## With specifying the minimum read size.
337 /// ```
338 /// use rumtk_core::base::{RUMResult, RUMVec};
339 /// use rumtk_core::buffers::*;
340 /// use rumtk_core::rumtk_read_stdin;
341 ///
342 /// fn test_read_stdin() -> RUMResult<RUMVec<u8>> {
343 /// rumtk_read_stdin!(1024)
344 /// }
345 ///
346 /// match test_read_stdin() {
347 /// Ok(s) => (),
348 /// Err(e) => panic!("Error reading stdin because => {}", e)
349 /// }
350 /// ```
351 ///
352 #[macro_export]
353 macro_rules! rumtk_read_stdin {
354 ( ) => {{
355 use $crate::cpu::CPU_PAGE_SIZE;
356 use $crate::cli::cli_utils::{read_stdin};
357 read_stdin(CPU_PAGE_SIZE * CPU_PAGE_SIZE)
358 }};
359 ( $min_expected_size:expr ) => {{
360 use $crate::cli::cli_utils::{read_stdin};
361 read_stdin($min_expected_size)
362 }};
363 }
364
365 ///
366 /// Writes [RUMString](crate::strings::RUMString) or [RUMBuffer](crate::types::RUMBuffer) to `stdout`.
367 ///
368 /// If the `binary` parameter is passed, we push the `message` parameter directly to `stdout`. the
369 /// `message` parameter has to be of type [RUMBuffer](crate::types::RUMBuffer).
370 ///
371 /// ## Example
372 ///
373 /// ### Default / Pushing a String
374 /// ```
375 /// use rumtk_core::rumtk_write_stdout;
376 ///
377 /// rumtk_write_stdout!("I ❤ my wife!");
378 /// ```
379 ///
380 /// ## Pushing Binary Buffer
381 /// ```
382 /// use rumtk_core::rumtk_write_stdout;
383 /// use rumtk_core::buffers::{new_random_rumbuffer, DEFAULT_BUFFER_CHUNK_SIZE};
384 ///
385 /// let buffer = new_random_rumbuffer::<DEFAULT_BUFFER_CHUNK_SIZE>();
386 /// rumtk_write_stdout!(buffer);
387 /// ```
388 ///
389 #[macro_export]
390 macro_rules! rumtk_write_stdout {
391 ( $message:expr ) => {{
392 use $crate::cli::cli_utils::write_stdout;
393 write_stdout(&$message)
394 }};
395 }
396
397 ///
398 /// Prints the mandatory GPL License Notice to terminal!
399 ///
400 /// # Example
401 /// ## Default
402 /// ```
403 /// use rumtk_core::rumtk_print_license_notice;
404 ///
405 /// rumtk_print_license_notice!();
406 /// ```
407 /// ## Program Only
408 /// ```
409 /// use rumtk_core::rumtk_print_license_notice;
410 ///
411 /// rumtk_print_license_notice!("RUMTK");
412 /// ```
413 /// ## Program + Year
414 /// ```
415 /// use rumtk_core::rumtk_print_license_notice;
416 ///
417 /// rumtk_print_license_notice!("RUMTK", "2025");
418 /// ```
419 /// ## Program + Year + Authors
420 /// ```
421 /// use rumtk_core::rumtk_print_license_notice;
422 ///
423 /// rumtk_print_license_notice!("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
424 /// ```
425 ///
426 #[macro_export]
427 macro_rules! rumtk_print_license_notice {
428 ( ) => {{
429 use $crate::cli::cli_utils::print_license_notice;
430
431 print_license_notice("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
432 }};
433 ( $program:expr ) => {{
434 use $crate::cli::cli_utils::print_license_notice;
435 print_license_notice(&$program, "2025", &vec!["2025", "Luis M. Santos, M.D."]);
436 }};
437 ( $program:expr, $year:expr ) => {{
438 use $crate::cli::cli_utils::print_license_notice;
439 print_license_notice(&$program, &$year, &vec!["Luis M. Santos, M.D."]);
440 }};
441 ( $program:expr, $year:expr, $authors:expr ) => {{
442 use $crate::cli::cli_utils::print_license_notice;
443 print_license_notice(&$program, &$year, &$authors);
444 }};
445 }
446
447 ///
448 /// Defines the CLI arguments of the program, parses the command line, and wires the message
449 /// processing logic.
450 ///
451 /// The macro expects an optional list of CLI argument definitions (same syntax accepted by
452 /// [rumtk_cli_define_args](crate::rumtk_cli_define_args)) followed by either the two message
453 /// handlers:
454 ///
455 /// + `ok` => Called when the incoming message could be deserialized into the expected type.
456 /// + `err` => Called with the raw bytes when deserialization was not possible.
457 ///
458 /// or a single piece of logic receiving the parsed arguments. In the latter case, the logic
459 /// owns the whole interface lifecycle and is called once with a reference to the parsed
460 /// arguments.
461 ///
462 /// The generated argument struct is named `RUMTKInterfaceArgs` and is available to the
463 /// handlers. If the `--daemon` flag is passed, the `ok`/`err` handlers are called in a loop for
464 /// every message coming through `stdin`. Otherwise, a single message is processed.
465 ///
466 /// ## Example
467 ///
468 /// ### Example 1 - With Parsed and Unparsed Message Closures
469 ///
470 /// ```no_run
471 /// use rumtk_core::base::{RUMResult, RUMVec};
472 /// use rumtk_core::strings::RUMString;
473 /// use rumtk_core::types::RUMCLIParser;
474 /// use rumtk_core::rumtk_cli_process;
475 ///
476 /// fn main() {
477 /// rumtk_cli_process!(
478 /// ///
479 /// /// Pretty print the outgoing message.
480 /// ///
481 /// #[arg(short, long)]
482 /// pretty: bool,
483 /// ///
484 /// /// Run in debug mode?
485 /// ///
486 /// #[arg(short, long)]
487 /// debug: bool,
488 /// |msg: RUMString, args: &RUMTKInterfaceArgs| -> RUMResult<RUMString> {
489 /// Ok(msg)
490 /// },
491 /// |data: RUMVec<u8>, args: &RUMTKInterfaceArgs| -> RUMResult<RUMString> {
492 /// Ok(RUMString::default())
493 /// }
494 /// );
495 /// }
496 /// ```
497 ///
498 /// ### Example 2 - With Raw Logic
499 ///
500 /// ```no_run
501 /// use rumtk_core::base::{RUMResult, RUMVec};
502 /// use rumtk_core::strings::RUMString;
503 /// use rumtk_core::types::RUMCLIParser;
504 /// use rumtk_core::rumtk_cli_process;
505 ///
506 /// fn main() {
507 /// rumtk_cli_process!(
508 /// ///
509 /// /// Pretty print the outgoing message.
510 /// ///
511 /// #[arg(short, long)]
512 /// pretty: bool,
513 /// ///
514 /// /// Run in debug mode?
515 /// ///
516 /// #[arg(short, long)]
517 /// debug: bool,
518 /// |args: &RUMTKInterfaceArgs| -> RUMResult<RUMString> {
519 /// Ok(RUMString::default())
520 /// }
521 /// );
522 /// }
523 /// ```
524 ///
525 /// ## Notes
526 ///
527 /// I let `Claude Opus 5` help complete this macro. I did not understand how to wire the
528 /// token tree muncher into the argument pattern to pass to [rumtk_cli_define_args](crate::rumtk_cli_define_args)
529 /// and the two additional arguments representing the closures to be executed if message parsing is successful or not.
530 ///
531 #[macro_export]
532 macro_rules! rumtk_cli_process {
533 (
534 @collect [$($cli_args:tt)*]
535 $(#[$field_meta:meta])+
536 $field_name:ident : $field_typ:ty,
537 $($rest:tt)*
538 ) => {
539 $crate::rumtk_cli_process!(
540 @collect [$($cli_args)* $(#[$field_meta])* $field_name : $field_typ,]
541 $($rest)*
542 )
543 };
544 (
545 @collect [$($cli_args:tt)*]
546 $field_name:ident : $field_typ:ty,
547 $($rest:tt)*
548 ) => {
549 $crate::rumtk_cli_process!(
550 @collect [$($cli_args)* $field_name : $field_typ,]
551 $($rest)*
552 )
553 };
554 (
555 @collect [$($cli_args:tt)*]
556 $logic:expr $(,)?
557 ) => {{
558 use $crate::cli::cli_utils::{process_message_loop, process_message, CliProcessor};
559 use $crate::types::RUMCLIParser;
560
561 $crate::rumtk_cli_define_args!($($cli_args)*);
562
563 let args = RUMTKInterfaceArgs::parse();
564
565 let r = match $logic {
566 CliProcessor::Direct(executor) => {
567 executor(&args)
568 },
569 CliProcessor::Message(executor) => {
570 if args.daemon {
571 Ok(process_message_loop(&args, &executor))
572 } else {
573 process_message(&args, &executor)
574 }
575 }
576 };
577
578 match r {
579 Ok(_) => {},
580 Err(e) => println!("Error: {}", e),
581 };
582 }};
583 (
584 $($tokens:tt)*
585 ) => {
586 $crate::rumtk_cli_process!(@collect [] $($tokens)*)
587 };
588 }
589}