rumtk_web/utils/app.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 Ethan Dixon
6 * Copyright (C) 2025 MedicalMasses L.L.C. <contact@medicalmasses.com>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21use crate::components::form::Forms;
22pub use crate::css::DEFAULT_OUT_CSS_DIR;
23use crate::pages::UserPages;
24pub use crate::utils::defaults::{DEFAULT_LISTENING_PORT, DEFAULT_LOCAL_LISTENING_ADDRESS};
25use crate::utils::matcher::*;
26use crate::{rumtk_web_api_process, rumtk_web_get_config, SharedAppState};
27use crate::{rumtk_web_fetch, RUMString};
28use rumtk_core::base::RUMResult;
29use rumtk_core::types::RUMTcpListener;
30use std::future::Future;
31
32use crate::api::UserAPIEndpoints;
33use axum::routing::{get, post};
34use axum::Router;
35use rumtk_core::rumtk_spawn_task;
36use rumtk_core::strings::rumtk_format;
37use tower_http::compression::{CompressionLayer, DefaultPredicate};
38use tower_http::services::ServeDir;
39
40pub const DEFAULT_UPLOAD_LIMIT: usize = 10240;
41
42async fn create_listener<F>(ctx: &AppContext<F>) -> RUMResult<RUMTcpListener>
43where
44 F: Future<Output = RUMResult<()>>,
45{
46 let mut ip = ctx.ip.clone().unwrap_or_else(|| {DEFAULT_LOCAL_LISTENING_ADDRESS.to_string()});
47
48 if ip.is_empty() {
49 ip = DEFAULT_LOCAL_LISTENING_ADDRESS.to_string();
50 }
51
52 let listening_ip = rumtk_format!(
53 "{}:{}",
54 ip,
55 ctx.port.clone().unwrap_or_else(|| {DEFAULT_LISTENING_PORT.parse().unwrap_or_default()})
56 );
57
58 println!("binding IP {}", listening_ip.as_str());
59 let listener = match RUMTcpListener::bind(listening_ip.as_str()).await {
60 Ok(listener) => listener,
61 Err(err) => return Err(rumtk_format!("There was an issue biding the listener. {}", err)),
62 };
63 println!("listening on {}", listener.local_addr().unwrap());
64
65 Ok(listener)
66}
67
68pub async fn run_app<F>(ctx: AppContext<F>) -> RUMResult<()>
69where
70 F: Future<Output = RUMResult<()>>,
71{
72 let comression_layer: CompressionLayer = CompressionLayer::new()
73 .br(true)
74 .deflate(true)
75 .gzip(true)
76 .zstd(true)
77 .compress_when(DefaultPredicate::new());
78 let app = Router::new()
79 /* Robots.txt */
80 .route("/robots.txt", get(rumtk_web_fetch!(default_robots_matcher)))
81 /* Jobs Queue */
82 .route("/jobs/", get(rumtk_web_fetch!(default_job_matcher)))
83 .route("/jobs/{*page}", get(rumtk_web_fetch!(default_job_matcher)))
84 /* Pages */
85 .route("/", get(rumtk_web_fetch!(default_page_matcher)))
86 .route("/{*page}", get(rumtk_web_fetch!(default_page_matcher)))
87 .layer(rumtk_web_get_config!(ctx.state).cors.clone().unwrap_or_default().build_cors_layer())
88 /* Post Handling */
89 .route("/api/", post(rumtk_web_api_process!(default_api_matcher)))
90 //.layer(DefaultBodyLimit::max(args.upload_limit))
91 .route(
92 "/api/{*page}",
93 post(rumtk_web_api_process!(default_api_matcher)),
94 )
95 //.layer(DefaultBodyLimit::max(args.upload_limit))
96 /* Services */
97 .nest_service("/static", ServeDir::new("static"))
98 .with_state(ctx.state.clone())
99 .layer(comression_layer);
100
101 match !ctx.switches.skip_serve {
102 true => {
103 let listener = create_listener(&ctx).await?;
104 // Begin the web app logic so we can serve the app.
105 let axum_app = async move || -> RUMResult<()> {
106 match axum::serve(listener, app).await
107 {
108 Ok(()) => Ok(()),
109 Err(e) => Err(rumtk_format!("There was an issue with the server: {}", e))
110 }
111 };
112 let axum_app_handle = rumtk_spawn_task!(axum_app());
113 // Run the custom logic if any. This is meant for processing CLI messages separately from the web app.
114 match ctx.logic {
115 Some(logic) => match logic.await {
116 Ok(()) => (),
117 Err(e) => return Err(rumtk_format!("There was an issue with the custom app logic: {}", e))
118 },
119 None => (),
120 };
121
122 match axum_app_handle.await {
123 Ok(r) => r,
124 Err(e) => Err(rumtk_format!("There was an issue running the server: {}", e))
125 }
126 },
127 false => Ok(()),
128 }
129}
130
131///
132/// Struct encapsulating custom-made items to register with the framework.
133///
134/// ## Pages
135/// The `pages` field accepts an optional of [UserPages] which is a vector of [PageItem](crate::pages::PageItem).
136///
137/// ```text
138/// vec![
139/// ("my_page", my_page_function),
140/// ...
141/// ];
142/// ```
143///
144/// The page function is of type [PageFunction](crate::utils::types::PageFunction).
145///
146/// It is important to understand that a `page` is a function that simply list the series of components to be rendered.
147/// We rely on `CSS` for the actual layout in 2D space. Therefore, a page function should not prescribe the page layout per se.
148///
149/// ## Components
150/// The `components` field takes an optional of [UserComponents] which is a vector of [UserComponentItem](crate::components::UserComponentItem).
151///
152/// ```text
153/// vec![
154/// ("my_component", my_component_function),
155/// ...
156/// ];
157/// ```
158///
159/// The component function is of type [PageFunction](crate::utils::types::ComponentFunction).
160///
161/// ## Forms
162/// The `forms` field takes an optional of [Forms] which is a vector of [FormItem](crate::components::form::FormItem).
163///
164/// ```text
165/// vec![
166/// ("my_form", my_form_function),
167/// ...
168/// ];
169/// ```
170///
171/// The form function is of type [FormBuilderFunction](crate::components::form::FormBuilderFunction).
172///
173/// Although a `form` is treated as a type of component in the framework, its implementation and behavior is closer to
174/// a `page` in that its main role is to define the vector of [FormElementBuilder](crate::components::form::FormElementBuilder).
175/// These element builder functions further renders the actual form component to be inserted in linear order. Again, these functions
176/// say nothing about the layout of the form as that is handled via `CSS`.
177///
178/// ## APIs
179/// The `apis` field takes an optional of [UserAPIEndpoints] which is a vector of [APIItem](crate::api::APIItem).
180///
181/// ```text
182/// vec![
183/// ("/my/api/endpoint", my_api_handler),
184/// ...
185/// ];
186/// ```
187///
188/// The api function is of type [APIFunction](crate::utils::types::APIFunction).
189///
190/// These API functions are your handlers directly mapped to the REST route you wish to intercept. This enables a
191/// simple key-value pair approach to defining API endpoints in your web app. These handlers can queue asynchronous
192/// pipeline jobs, return HTML fragments, redirect the current page somewhere else, or a combination of these.
193/// It is a powerful interface for organizing your routing.
194///
195#[derive(Default, Debug, PartialEq, Clone)]
196pub struct AppComponents<'a> {
197 pub pages: Option<UserPages<'a>>,
198 pub forms: Option<Forms<'a>>,
199 pub apis: Option<UserAPIEndpoints<'a>>,
200}
201
202///
203/// Struct for defining the global switches to drive the initialization of the web app. This struct
204/// works hand in hand with [AppComponents].
205///
206#[derive(Default, Debug, PartialEq, Clone)]
207pub struct AppSwitches {
208 pub skip_serve: bool,
209 pub skip_default_css: bool,
210 pub skip_cli_args: bool,
211}
212
213impl AppSwitches {
214 pub fn from_slice(switches: &[bool]) -> Self {
215 match switches.len() {
216 0 => AppSwitches::default(),
217 1 => AppSwitches {
218 skip_serve: switches[0],
219 ..Default::default()
220 },
221 2 => AppSwitches {
222 skip_serve: switches[0],
223 skip_default_css: switches[1],
224 ..Default::default()
225 },
226 _ => AppSwitches {
227 skip_serve: switches[0],
228 skip_default_css: switches[1],
229 skip_cli_args: switches[2],
230 },
231 }
232 }
233}
234
235impl From<&[bool]> for AppSwitches {
236 fn from(switches: &[bool]) -> Self {
237 AppSwitches::from_slice(switches)
238 }
239}
240
241impl<const N: usize> From<[bool; N]> for AppSwitches {
242 fn from(switches: [bool; N]) -> Self {
243 AppSwitches::from_slice(&switches)
244 }
245}
246
247///
248/// Struct encapsulating custom-made items to register with the framework.
249///
250///
251#[derive(Default, Debug, Clone)]
252pub struct AppContext<F: Future<Output = RUMResult<()>>> {
253 pub ip: Option<RUMString>,
254 pub port: Option<u16>,
255 pub logic: Option<F>,
256 pub components: AppComponents<'static>,
257 pub switches: AppSwitches,
258 pub state: SharedAppState,
259}
260
261impl<F> AppContext<F>
262where
263 F: Future<Output = RUMResult<()>>
264{
265 pub fn new() -> AppContext<F> {
266 AppContext {
267 ip: None,
268 port: None,
269 logic: None,
270 components: AppComponents::default(),
271 switches: AppSwitches::default(),
272 state: SharedAppState::default(),
273 }
274 }
275
276 pub fn init_ip(mut self, ip: RUMString) -> AppContext<F> {
277 if self.ip.is_none() {
278 self.ip = Some(ip);
279 }
280
281 self
282 }
283
284 pub fn init_port(mut self, port: u16) -> AppContext<F> {
285 if self.port.is_none() {
286 self.port = Some(port);
287 }
288 self
289 }
290
291 pub fn init_logic(mut self, logic: F) -> AppContext<F> {
292 if self.logic.is_none() {
293 self.logic = Some(logic);
294 }
295
296 self
297 }
298
299 pub fn init_components(mut self, components: AppComponents<'static>) -> AppContext<F> {
300 self.components = components;
301 self
302 }
303
304 pub fn init_switches(mut self, switches: AppSwitches) -> AppContext<F> {
305 self.switches = switches;
306 self
307 }
308
309 pub fn init_state(mut self, state: SharedAppState) -> AppContext<F> {
310 self.state = state;
311 self
312 }
313}
314
315///
316/// Convenience macro for quickly building the [AppComponents] object. Feel free to pass an instance of
317/// [AppComponents] directly to [run_app] or [rumtk_web_run_app](crate::rumtk_web_run_app).
318///
319/// Passing no parameters generates an "empty" instance, meaning you would be asking the framework that you only
320/// care about built-in components. This also implies you do not want to process API endpoints.
321///
322/// ## Examples
323///
324/// ### Without Parameters
325/// ```
326/// use crate::rumtk_web::AppComponents;
327/// use crate::rumtk_web::rumtk_web_register_app_components;
328///
329/// let expected = AppComponents::default();
330/// let result = rumtk_web_register_app_components!();
331///
332/// assert_eq!(result, expected, "Default macro-generated instance of AppComponents are not the same!");
333///
334/// ```
335///
336/// ### With Existing Page
337/// ```
338/// use rumtk_web::pages::UserPages;
339/// use crate::rumtk_web::AppComponents;
340/// use crate::rumtk_web::pages::index::index;
341/// use crate::rumtk_web::rumtk_web_register_app_components;
342///
343/// let my_pages: UserPages = vec![
344/// ("myindex", index)
345/// ];
346/// let expected = AppComponents {
347/// pages: Some(my_pages.clone()),
348/// forms: None,
349/// apis: None,
350/// };
351/// let result = rumtk_web_register_app_components!(my_pages);
352///
353/// assert_eq!(result, expected, "Default macro-generated instance of AppComponents are not the same!");
354///
355/// ```
356///
357/// ### With Existing Page and Component and Form
358/// ```
359/// use rumtk_core::strings::RUMString;
360/// use rumtk_web::{AppComponents, SharedAppState};
361/// use rumtk_web::pages::UserPages;
362/// use rumtk_web::components::form::{FormElementBuilder, FormElements, Forms};
363/// use rumtk_web::pages::index::index;
364/// use rumtk_web::components::form::props::InputProps;
365/// use rumtk_web::rumtk_web_register_app_components;
366///
367/// fn upload_form(builder: FormElementBuilder, _state: &SharedAppState) -> FormElements {
368/// vec![
369/// builder(
370/// "input",
371/// "",
372/// InputProps {
373/// id: Some("file"),
374/// name: Some("file"),
375/// for_element: None,
376/// typ: Some("file"),
377/// value: None,
378/// max: None,
379/// placeholder: Some("path/to/file"),
380/// pattern: None,
381/// accept: Some(".pdf,application/pdf"),
382/// alt: None,
383/// aria_label: Some("PDF File Picker"),
384/// event_handlers: None,
385/// max_length: None,
386/// min_length: None,
387/// autocapitalize: false,
388/// autocomplete: false,
389/// autocorrect: false,
390/// autofocus: false,
391/// disabled: false,
392/// hidden: false,
393/// required: true,
394/// multiple: false,
395/// },
396/// ""
397/// ),
398/// builder(
399/// "input",
400/// "",
401/// InputProps {
402/// id: Some("submit"),
403/// name: None,
404/// for_element: None,
405/// typ: Some("submit"),
406/// value: Some("Send"),
407/// max: None,
408/// placeholder: None,
409/// pattern: None,
410/// accept: None,
411/// alt: None,
412/// aria_label: Some("PDF File Submit Button"),
413/// event_handlers: None,
414/// max_length: None,
415/// min_length: None,
416/// autocapitalize: false,
417/// autocomplete: false,
418/// autocorrect: false,
419/// autofocus: false,
420/// disabled: false,
421/// hidden: false,
422/// required: false,
423/// multiple: false,
424/// },
425/// "f18"
426/// ),
427/// builder(
428/// "progress",
429/// "",
430/// InputProps {
431/// id: Some("progress"),
432/// name: None,
433/// for_element: None,
434/// typ: None,
435/// value: Some("0"),
436/// max: Some("100"),
437/// placeholder: None,
438/// pattern: None,
439/// accept: None,
440/// alt: None,
441/// aria_label: Some("PDF File Submit Progress Bar"),
442/// event_handlers: None,
443/// max_length: None,
444/// min_length: None,
445/// autocapitalize: false,
446/// autocomplete: false,
447/// autocorrect: false,
448/// autofocus: false,
449/// disabled: false,
450/// hidden: true,
451/// required: false,
452/// multiple: false,
453/// },
454/// ""
455/// ),
456/// ]
457/// }
458///
459/// let my_pages: UserPages = vec![
460/// ("myindex", index)
461/// ];
462/// let my_forms: Forms = vec![
463/// ("myform", upload_form)
464/// ];
465/// let expected = AppComponents {
466/// pages: Some(my_pages.clone()),
467/// forms: Some(my_forms.clone()),
468/// apis: None,
469/// };
470/// let result = rumtk_web_register_app_components!(my_pages, my_forms);
471///
472/// assert_eq!(result, expected, "Default macro-generated instance of AppComponents are not the same!");
473///
474/// ```
475///
476/// ### With Existing Page and Component and Form and API Endpoint
477/// ```
478/// use rumtk_core::{rumtk_pipeline_run_async, rumtk_pipeline_command};
479/// use rumtk_core::strings::{RUMString, RUMStringConversions, RUMArrayConversions};
480/// use rumtk_web::{rumtk_web_params_map, rumtk_web_post_process_html, APIPath, AppComponents, FormData, HTMLResult, RUMWebData, RUMWebResponse, SharedAppState};
481/// use rumtk_web::{rumtk_web_get_job_manager, rumtk_web_render_component, rumtk_web_render_page_contents};
482/// use rumtk_web::api::UserAPIEndpoints;
483/// use rumtk_web::pages::UserPages;
484/// use rumtk_web::components::form::{FormElementBuilder, FormElements, Forms};
485/// use rumtk_web::pages::index::index;
486/// use rumtk_web::components::form::props::InputProps;
487/// use rumtk_web::components::job_loader::{job_loader, JobLoader};
488/// use rumtk_web::jobs::{JobResult};
489/// use rumtk_web::utils::defaults::{PARAMS_TARGET, PARAMS_ID};
490/// use rumtk_web::ComponentResult;
491/// use rumtk_web::components::sanitize::sanitized;
492/// use rumtk_web::rumtk_web_register_app_components;
493///
494/// async fn upload_processor(form: FormData) -> JobResult {
495/// let id = form.form.get("file").unwrap();
496/// let file = form.files.get(id).unwrap();
497///
498/// let result = rumtk_pipeline_run_async!(
499/// &vec![
500/// rumtk_pipeline_command!("cat"),
501/// rumtk_pipeline_command!("wc")
502/// ],
503/// &file.clone()
504/// ).await?;
505///
506/// let sanitized = sanitized(result.to_vec().to_string()?);
507/// Ok(Some(sanitized?))
508/// }
509///
510/// pub fn process_upload(path: APIPath, params: RUMWebData, form: FormData, state: SharedAppState) -> HTMLResult {
511/// let job_id = rumtk_web_get_job_manager!()?.spawn_task(upload_processor(form))?;
512///
513/// let params = rumtk_web_params_map!([(PARAMS_ID, job_id)]);
514/// let viewer = job_loader(&[], params.get_inner(), state)?.to_string();
515///
516///
517/// rumtk_web_render_page_contents!(
518/// &vec![
519/// viewer
520/// ]
521/// )
522/// }
523///
524/// fn upload_form(builder: FormElementBuilder, _state: &SharedAppState) -> FormElements {
525/// vec![
526/// builder(
527/// "input",
528/// "",
529/// InputProps {
530/// id: Some("file"),
531/// name: Some("file"),
532/// for_element: None,
533/// typ: Some("file"),
534/// value: None,
535/// max: None,
536/// placeholder: Some("path/to/file"),
537/// pattern: None,
538/// accept: Some(".pdf,application/pdf"),
539/// alt: None,
540/// aria_label: Some("PDF File Picker"),
541/// event_handlers: None,
542/// max_length: None,
543/// min_length: None,
544/// autocapitalize: false,
545/// autocomplete: false,
546/// autocorrect: false,
547/// autofocus: false,
548/// disabled: false,
549/// hidden: false,
550/// required: true,
551/// multiple: false,
552/// },
553/// ""
554/// ),
555/// builder(
556/// "input",
557/// "",
558/// InputProps {
559/// id: Some("submit"),
560/// name: None,
561/// for_element: None,
562/// typ: Some("submit"),
563/// value: Some("Send"),
564/// max: None,
565/// placeholder: None,
566/// pattern: None,
567/// accept: None,
568/// alt: None,
569/// aria_label: Some("PDF File Submit Button"),
570/// event_handlers: None,
571/// max_length: None,
572/// min_length: None,
573/// autocapitalize: false,
574/// autocomplete: false,
575/// autocorrect: false,
576/// autofocus: false,
577/// disabled: false,
578/// hidden: false,
579/// required: false,
580/// multiple: false,
581/// },
582/// "f18"
583/// ),
584/// builder(
585/// "progress",
586/// "",
587/// InputProps {
588/// id: Some("progress"),
589/// name: None,
590/// for_element: None,
591/// typ: None,
592/// value: Some("0"),
593/// max: Some("100"),
594/// placeholder: None,
595/// pattern: None,
596/// accept: None,
597/// alt: None,
598/// aria_label: Some("PDF File Submit Progress Bar"),
599/// event_handlers: None,
600/// max_length: None,
601/// min_length: None,
602/// autocapitalize: false,
603/// autocomplete: false,
604/// autocorrect: false,
605/// autofocus: false,
606/// disabled: false,
607/// hidden: true,
608/// required: false,
609/// multiple: false,
610/// },
611/// ""
612/// ),
613/// ]
614/// }
615///
616/// let my_pages: UserPages = vec![
617/// ("myindex", index)
618/// ];
619/// let my_forms: Forms = vec![
620/// ("myform", upload_form)
621/// ];
622/// let my_endpoints: UserAPIEndpoints = vec![
623/// ("/api/upload", process_upload)
624/// ];
625/// let expected = AppComponents {
626/// pages: Some(my_pages.clone()),
627/// forms: Some(my_forms.clone()),
628/// apis: Some(my_endpoints.clone()),
629/// };
630/// let result = rumtk_web_register_app_components!(my_pages, my_forms, my_endpoints);
631///
632/// assert_eq!(result, expected, "Default macro-generated instance of AppComponents are not the same!");
633///
634/// ```
635///
636#[macro_export]
637macro_rules! rumtk_web_register_app_components {
638 ( ) => {{
639 use $crate::utils::app::AppComponents;
640
641 AppComponents::default()
642 }};
643 ( $pages:expr ) => {{
644 use $crate::utils::app::AppComponents;
645
646 AppComponents {
647 pages: Some($pages),
648 forms: None,
649 apis: None,
650 }
651 }};
652 ( $pages:expr, $forms:expr ) => {{
653 use $crate::utils::app::AppComponents;
654
655 AppComponents {
656 pages: Some($pages),
657 forms: Some($forms),
658 apis: None,
659 }
660 }};
661 ( $pages:expr, $forms:expr, $apis:expr ) => {{
662 use $crate::utils::app::AppComponents;
663
664 AppComponents {
665 pages: Some($pages),
666 forms: Some($forms),
667 apis: Some($apis),
668 }
669 }};
670}
671
672///
673/// Convenience macro for generating a [AppSwitches] instance containing the boolean options a
674/// framework consumer would like to opt-in.
675///
676/// ## Examples
677/// ```
678/// use rumtk_web::AppSwitches;
679/// use rumtk_web::{rumtk_web_register_app_switches};
680///
681/// let expected = AppSwitches {
682/// skip_serve: true,
683/// skip_default_css: false,
684/// ..Default::default()
685/// };
686/// let switches = rumtk_web_register_app_switches!(true);
687///
688/// assert_eq!(switches, expected, "The switches constructed to config app does not match the expected.");
689/// ```
690///
691#[macro_export]
692macro_rules! rumtk_web_register_app_switches {
693 ( ) => {{
694 use $crate::utils::app::AppSwitches;
695
696 AppSwitches::default()
697 }};
698 ( $($switch:expr),+ ) => {{
699 use $crate::utils::app::AppSwitches;
700
701 AppSwitches::from([$($switch),+])
702 }};
703}
704
705///
706/// Initializes a Context structure used for runtime configuration of the app in addition to the
707/// JSON configuration.
708///
709/// ## Usage Examples
710/// ```
711/// use rumtk_web::{rumtk_web_register_app_context, rumtk_web_register_app_switches};
712/// use rumtk_web::utils::app::{AppComponents, AppSwitches};
713///
714/// rumtk_web_register_app_context!();
715/// rumtk_web_register_app_context!(AppComponents::default());
716/// rumtk_web_register_app_context!(AppComponents::default(), AppSwitches::default());
717/// rumtk_web_register_app_context!(AppComponents::default(), AppSwitches::default(), 3001);
718/// rumtk_web_register_app_context!(AppComponents::default(), AppSwitches::default(), 3001, async || Ok(()));
719/// ```
720///
721/// ## Usage Signature
722/// Below are the supported macro signatures:
723///
724/// ```text
725/// - ()
726/// - ( app_components )
727/// - ( app_components, app_switches )
728/// - ( app_components, app_switches, port )
729/// - ( app_components, app_switches, port, || -> rumtk_core::base::RUMResult<()> { Ok(()) } )
730/// ```
731///
732/// ## Note
733/// In some cases, this struct is used to override the typical behavior since the `ip`, `port`, and
734/// `logic` fields are initialized only once. Meaning, we can route the system to use specific ports
735/// during testing or statically in the program and follow the CLI arguments all other times.
736///
737#[macro_export]
738macro_rules! rumtk_web_register_app_context {
739 ( ) => {{
740 $crate::rumtk_web_register_app_context!($crate::utils::app::AppComponents::default())
741 }};
742 (
743 $app_components:expr
744 ) => {{
745 $crate::rumtk_web_register_app_context!(
746 $app_components,
747 $crate::rumtk_web_register_app_switches!(),
748 $crate::utils::app::DEFAULT_LISTENING_PORT.parse::<u16>().unwrap_or_default(),
749 async || -> rumtk_core::base::RUMResult<()> { Ok(()) }
750 )
751 }};
752 (
753 $app_components:expr,
754 $app_switches:expr $(,)?
755 ) => {{
756 $crate::rumtk_web_register_app_context!(
757 $app_components,
758 $app_switches,
759 $crate::utils::app::DEFAULT_LISTENING_PORT.parse::<u16>().unwrap_or_default(),
760 async || -> rumtk_core::base::RUMResult<()> { Ok(()) }
761 )
762 }};
763 (
764 $app_components:expr,
765 $app_switches:expr,
766 $port:expr
767 ) => {{
768 $crate::rumtk_web_register_app_context!(
769 $app_components,
770 $app_switches,
771 $port,
772 async || -> rumtk_core::base::RUMResult<()> { Ok(()) }
773 )
774 }};
775 (
776 $app_components:expr,
777 $app_switches:expr,
778 $port:expr,
779 $hook:expr
780 ) => {{
781 use $crate::utils::app::AppContext;
782
783 AppContext::new()
784 .init_components($app_components.clone())
785 .init_switches($app_switches.clone())
786 .init_port($port)
787 .init_logic($hook())
788 }};
789}
790
791///
792/// This is the main macro for defining your applet and launching it.
793/// Usage is very simple and the only decision from a user is whether to pass a list of
794/// [UserPages](UserPages) or a list of [UserPages](UserPages) and a list
795/// of [UserComponents](UserComponents).
796///
797/// These lists are used to automatically register your pages
798/// (e.g. `/index => ('index', my_index_function)`) and your custom components
799/// (e.g. `button => ('button', my_button_function)`
800///
801/// This macro will load CSS from predefined sources, concatenate their contents with predefined CSS,
802/// minified the concatenated results, and generate a bundle css file containing the minified results.
803/// The CSS bundle is written to file `./static/css/bundle.min.css`.
804///
805/// ***Note: anything in ./static will be considered static assets that need to be served.***
806///
807/// This macro will also parse the command line automatically with a few predefined options and
808/// use that information to override the config defaults.
809///
810/// By default, the app is launched to `127.0.0.1:3000` which is the loopback address.
811///
812/// App is served with the best compression algorithm allowed by the client browser.
813///
814/// For testing purposes, the function
815///
816/// ## Example Usage
817///
818/// ### With Page and Component definition
819/// ```
820/// use rumtk_core::strings::{rumtk_format};
821/// use rumtk_web::{rumtk_web_run_app, rumtk_web_register_app_components, rumtk_web_render_component, rumtk_web_render_template, rumtk_web_get_text_item, rumtk_web_register_app_switches, rumtk_web_get_config, rumtk_web_params_map};
822/// use rumtk_web::components::form::{FormElementBuilder, props::InputProps, FormElements};
823/// use rumtk_web::{SharedAppState, RenderedPageComponentsResult};
824/// use rumtk_web::{APIPath, URLPath, URLParams, HTMLResult, RUMString, RouterForm, FormData, RUMWebData, AppConf};
825/// use rumtk_web::components::portrait_card::portrait_card;
826/// use rumtk_web::components::layouts::spacer::vspacer;
827/// use rumtk_web::components::text_card::text_card;
828/// use rumtk_web::components::title::title;
829/// use rumtk_web::ComponentResult;
830/// use rumtk_web::components::job_loader::JobLoader;
831/// use rumtk_web::defaults::{DEFAULT_TEXT_ITEM, PARAMS_CONTENTS, PARAMS_CSS_CLASS, PARAMS_TYPE};
832/// use rumtk_web::utils::types::RUMWebTemplate;
833///
834///
835///
836///
837/// // About page
838/// pub fn about(app_state: SharedAppState) -> RenderedPageComponentsResult {
839/// let title_coop_params = rumtk_web_params_map!([(PARAMS_TYPE, "coop_values")]);
840/// let title_coop = title(&[], title_coop_params.get_inner(), app_state.clone())?.to_string();
841///
842/// let title_team_params = rumtk_web_params_map!([(PARAMS_TYPE, "meet_the_team")]);
843/// let title_team = title(&[], title_team_params.get_inner(), app_state.clone())?.to_string();
844///
845/// let text_card_story_params = rumtk_web_params_map!([(PARAMS_TYPE, "story")]);
846/// let text_card_story = text_card(&[], text_card_story_params.get_inner(), app_state.clone())?.to_string();
847///
848/// let text_card_coop_params = rumtk_web_params_map!([(PARAMS_TYPE, "coop_values")]);
849/// let text_card_coop = text_card(&[], text_card_coop_params.get_inner(), app_state.clone())?.to_string();
850///
851/// let portrait_card_params = rumtk_web_params_map!([("section", "company"), (PARAMS_TYPE, "personnel")]);
852/// let portrait_card = portrait_card(&[], portrait_card_params.get_inner(), app_state.clone())?.to_string();
853///
854/// let spacer_5 = vspacer(5)?.to_string();
855///
856/// Ok(vec![
857/// text_card_story,
858/// spacer_5.clone(),
859/// title_coop,
860/// text_card_coop,
861/// spacer_5,
862/// title_team,
863/// portrait_card
864/// ])
865/// }
866///
867/// //Custom component
868/// #[derive(RUMWebTemplate, Debug)]
869/// #[template(
870/// source = "
871/// {% if custom_css_enabled %}
872/// <link href='/static/components/div.css' rel='stylesheet'>
873/// {% endif %}
874/// <div class='div-{{css_class}}'>{{contents|safe}}</div>
875/// ",
876/// ext = "html"
877/// )]
878/// struct MyDiv {
879/// contents: RUMString,
880/// css_class: RUMString,
881/// custom_css_enabled: bool,
882/// }
883///
884/// fn my_div(path_components: URLPath, params: URLParams, state: SharedAppState) -> ComponentResult<MyDiv> {
885/// let contents = rumtk_web_get_text_item!(params, PARAMS_CONTENTS, DEFAULT_TEXT_ITEM);
886/// let css_class = rumtk_web_get_text_item!(params, PARAMS_CSS_CLASS, DEFAULT_TEXT_ITEM);
887///
888/// let custom_css_enabled = rumtk_web_get_config!(state).flags.custom_css;
889///
890/// Ok(MyDiv {
891/// contents: RUMString::from(contents),
892/// css_class: RUMString::from(css_class),
893/// custom_css_enabled
894/// })
895/// }
896///
897/// fn my_form (builder: FormElementBuilder, _state: &SharedAppState) -> FormElements {
898/// vec![
899/// builder("input", "", InputProps::default(), "default")
900/// ]
901/// }
902///
903/// fn my_api_handler(path: APIPath, params: RUMWebData, form: FormData, state: SharedAppState) -> HTMLResult {
904/// Err(rumtk_format!(
905/// "No handler registered for API endpoint => {}",
906/// path
907/// ))
908/// }
909///
910/// //Requesting to immediately exit instead of indefinitely serving pages so this example can be used as a unit test.
911/// let skip_serve = true;
912/// let skip_default_css = false;
913///
914/// let app_components = rumtk_web_register_app_components!(
915/// vec![("about", about)],
916/// vec![("my_form", my_form)], //Optional, can be omitted alongside the skip_serve flag
917/// vec![("v2/add", my_api_handler)] //Optional, can be omitted alongside the skip_serve flag
918/// );
919/// let app_switches = rumtk_web_register_app_switches!(
920/// skip_serve, //Omit in production code. This is used so that this example can work as a unit test.
921/// skip_default_css //Omit in production code. This is used so that this example can work as a unit test.
922/// );
923/// let result = rumtk_web_run_app!(
924/// app_components,
925/// app_switches
926/// );
927/// ```
928///
929/// ### Example of Usage
930/// ```no_run
931/// use rumtk_web::{rumtk_web_run_app, rumtk_web_register_app_switches};
932/// use rumtk_web::utils::app::{AppComponents, AppSwitches};
933///
934/// //Requesting to immediately exit instead of indefinitely serving pages so this example can be used as a unit test.
935/// let skip_serve = true;
936/// let skip_default_css = false;
937/// let app_switches = rumtk_web_register_app_switches!(
938/// skip_serve, //Omit in production code. This is used so that this example can work as a unit test.
939/// skip_default_css //Omit in production code. This is used so that this example can work as a unit test.
940/// );
941///
942/// rumtk_web_run_app!();
943/// rumtk_web_run_app!([]);
944/// rumtk_web_run_app!([#[arg(long)] extra: bool]);
945/// rumtk_web_run_app!(AppComponents::default(), app_switches);
946/// rumtk_web_run_app!(AppComponents::default(), app_switches, 3001);
947/// rumtk_web_run_app!(AppComponents::default(), app_switches, 3001, async || Ok(()));
948/// rumtk_web_run_app!([#[arg(long)] extra: bool], AppComponents::default());
949/// rumtk_web_run_app!([#[arg(long)] extra: bool], AppComponents::default(), app_switches);
950/// rumtk_web_run_app!([#[arg(long)] extra: bool], AppComponents::default(), app_switches, 3001);
951/// rumtk_web_run_app!([#[arg(long)] extra: bool], AppComponents::default(), app_switches, 3001, async || Ok(()));
952/// ```
953///
954/// ## Signatures & Usages
955///
956/// This is a complex macro that is trying to be backwards compatible with the old prescribed way
957/// of producing a web applet. It is also trying to allow future applets to specify new flags and even
958/// a closure hook to perform further initialization of the framework based on the new flags.
959///
960/// Below are the supported macro signatures:
961///
962/// ```text
963/// - ()
964/// - ( pretty: bool )
965/// - ( pretty: bool, app_components )
966/// - ( pretty: bool, app_components, app_switches )
967/// - ( pretty: bool, app_components, app_switches, port )
968/// - ( pretty: bool, app_components, app_switches, port, || -> rumtk_core::base::RUMResult<()> { Ok(()) } )
969/// - ( app_components )
970/// - ( app_components, app_switches )
971/// - ( app_components, app_switches, port )
972/// - ( app_components, app_switches, port, || -> rumtk_core::base::RUMResult<()> { Ok(()) } )
973/// ```
974///
975#[macro_export]
976macro_rules! rumtk_web_run_app {
977 (
978 [
979 $(
980 $(#[$field_meta:meta])*
981 $field_name:ident : $field_typ:ty
982 ),* $(,)?
983 ],
984 $app_components:expr,
985 $switches:expr,
986 $port:expr,
987 $hook:expr $(,)?
988 ) => {{
989 $crate::rumtk_web_run_app!(
990 @collect [$($(#[$field_meta])* $field_name : $field_typ,)*],
991 $crate::rumtk_web_register_app_context!($app_components, $switches, $port, $hook)
992 )
993 }};
994 (
995 [
996 $(
997 $(#[$field_meta:meta])*
998 $field_name:ident : $field_typ:ty
999 ),* $(,)?
1000 ],
1001 $app_components:expr,
1002 $switches:expr,
1003 $port:expr
1004 ) => {{
1005 use rumtk_core;
1006 $crate::rumtk_web_run_app!(
1007 @collect [$($(#[$field_meta])* $field_name : $field_typ,)*],
1008 $crate::rumtk_web_register_app_context!($app_components, $switches, $port)
1009 )
1010 }};
1011 (
1012 [
1013 $(
1014 $(#[$field_meta:meta])*
1015 $field_name:ident : $field_typ:ty
1016 ),* $(,)?
1017 ],
1018 $app_components:expr,
1019 $switches:expr $(,)?
1020 ) => {{
1021 use rumtk_core;
1022 $crate::rumtk_web_run_app!(
1023 @collect [$($(#[$field_meta])* $field_name : $field_typ,)*],
1024 $crate::rumtk_web_register_app_context!($app_components, $switches)
1025 )
1026 }};
1027 (
1028 [
1029 $(
1030 $(#[$field_meta:meta])*
1031 $field_name:ident : $field_typ:ty
1032 ),* $(,)?
1033 ],
1034 $app_components:expr $(,)?
1035 ) => {{
1036 $crate::rumtk_web_run_app!(
1037 @collect [$($(#[$field_meta])* $field_name : $field_typ,)*],
1038 $crate::rumtk_web_register_app_context!($app_components)
1039 )
1040 }};
1041 (
1042 [
1043 $(
1044 $(#[$field_meta:meta])*
1045 $field_name:ident : $field_typ:ty
1046 ),* $(,)?
1047 ] $(,)?
1048 ) => {{
1049 $crate::rumtk_web_run_app!(
1050 @collect [$($(#[$field_meta])* $field_name : $field_typ,)*],
1051 $crate::rumtk_web_register_app_context!()
1052 )
1053 }};
1054 ( ) => {{
1055 $crate::rumtk_web_run_app!([])
1056 }};
1057 (
1058 $app_components:expr,
1059 $switches:expr,
1060 $port:expr,
1061 $hook:expr $(,)?
1062 ) => {{
1063 $crate::rumtk_web_run_app!(
1064 @collect [],
1065 $crate::rumtk_web_register_app_context!($app_components, $switches, $port, $hook)
1066 )
1067 }};
1068 (
1069 $app_components:expr,
1070 $switches:expr,
1071 $port:expr $(,)?
1072 ) => {{
1073 $crate::rumtk_web_run_app!(
1074 @collect [],
1075 $crate::rumtk_web_register_app_context!($app_components, $switches, $port)
1076 )
1077 }};
1078 (
1079 $app_components:expr,
1080 $switches:expr $(,)?
1081 ) => {{
1082 $crate::rumtk_web_run_app!(
1083 @collect [],
1084 $crate::rumtk_web_register_app_context!($app_components, $switches)
1085 )
1086 }};
1087 (
1088 $app_components:expr $(,)?
1089 ) => {{
1090 $crate::rumtk_web_run_app!(
1091 @collect [],
1092 $crate::rumtk_web_register_app_context!($app_components)
1093 )
1094 }};
1095 (
1096 @collect [$($cli_args:tt)*],
1097 $context:expr $(,)?
1098 ) => {{
1099 use rumtk_core::base::RUMResult;
1100 use rumtk_core::strings::RUMString;
1101 use rumtk_core::{rumtk_cli_process, rumtk_resolve_task};
1102 use $crate::{
1103 rumtk_web_load_conf, rumtk_web_init_pages, rumtk_web_init_forms,
1104 rumtk_web_init_api_endpoints, rumtk_web_compile_css_bundle,
1105 rumtk_web_init_job_manager
1106 };
1107 use $crate::utils::app::{
1108 DEFAULT_OUT_CSS_DIR,
1109 DEFAULT_LOCAL_LISTENING_ADDRESS,
1110 DEFAULT_LISTENING_PORT,
1111 DEFAULT_UPLOAD_LIMIT
1112 };
1113 use $crate::utils::app::{
1114 AppComponents,
1115 AppSwitches
1116 };
1117 use $crate::utils::app::{
1118 run_app
1119 };
1120 use clap;
1121
1122 rumtk_cli_process!(
1123 @collect [$($cli_args)*]
1124 ///
1125 /// Website title to use internally. It can be omitted if defined in the app.json config file
1126 /// bundled with your app.
1127 ///
1128 #[arg(long, default_value = "")]
1129 title: RUMString,
1130 ///
1131 /// Website description string. It can be omitted if defined in the app.json config file
1132 /// bundled with your app.
1133 ///
1134 #[arg(long, default_value = "")]
1135 description: RUMString,
1136 ///
1137 /// Company to display in website.
1138 ///
1139 #[arg(long, default_value = "")]
1140 company: RUMString,
1141 ///
1142 /// Copyright year to display in website.
1143 ///
1144 #[arg(short, long, default_value = "")]
1145 copyright: RUMString,
1146 ///
1147 /// Directory to scan on startup to find custom CSS sources to bundle into a minified CSS file
1148 /// that can be quickly pulled by the app client side.
1149 ///
1150 /// This option can provide an alternative to direct component retrieval of CSS fragments.
1151 /// Meaning, you could bundle all of your fragments into the master bundle at startup and
1152 /// turn off component level ```custom_css_enabled``` option in the ```app.json``` config.
1153 ///
1154 #[arg(long, default_value = DEFAULT_OUT_CSS_DIR)]
1155 css_source_dir: RUMString,
1156 ///
1157 /// IP address to bind!
1158 ///
1159 #[arg(short, long, default_value = DEFAULT_LOCAL_LISTENING_ADDRESS)]
1160 ip: RUMString,
1161 ///
1162 /// Port to bind!
1163 ///
1164 #[arg(short, long, default_value = DEFAULT_LISTENING_PORT, value_parser = clap::value_parser!(u16).range(1024..=65535))]
1165 port: u16,
1166 ///
1167 /// Specify the size limit for a file upload post request.
1168 ///
1169 #[arg(long, default_value_t = DEFAULT_UPLOAD_LIMIT)]
1170 upload_limit: usize,
1171 ///
1172 /// How many threads to use to serve the website. By default, we use
1173 /// ```get_default_system_thread_count()``` from ```rumtk-core``` to detect the total count of
1174 /// cpus available. We use the system's total count of cpus by default.
1175 ///
1176 #[arg(long, default_value_t = false)]
1177 skip_default_css: bool,
1178 Direct(|args: &RUMTKInterfaceArgs| -> RUMResult<()> {
1179 let state = rumtk_web_load_conf!(&*args);
1180
1181 let context = $context
1182 .init_ip(args.ip.clone())
1183 .init_port(args.port.clone())
1184 .init_state(state);
1185
1186 rumtk_web_init_pages!(context.components.pages.clone());
1187 rumtk_web_init_forms!(context.components.forms.clone(), context.state);
1188 rumtk_web_init_api_endpoints!(context.components.apis.clone());
1189 rumtk_web_compile_css_bundle!(
1190 &args.css_source_dir,
1191 &args.skip_default_css | context.switches.skip_default_css
1192 );
1193
1194 rumtk_web_init_job_manager!(&args.threads);
1195
1196 let task = run_app(context);
1197 rumtk_resolve_task!(task)
1198 })
1199 );
1200 }};
1201}