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.
5 * Copyright (C) 2025 Nick Stephenson
6 * Copyright (C) 2025 Ethan Dixon
7 * Copyright (C) 2025 MedicalMasses L.L.C.
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23use crate::components::{form::Forms, UserComponents};
24use crate::css::DEFAULT_OUT_CSS_DIR;
25use crate::pages::UserPages;
26use crate::utils::defaults::DEFAULT_LOCAL_LISTENING_ADDRESS;
27use crate::utils::matcher::*;
28use crate::{
29 rumtk_web_api_process, rumtk_web_compile_css_bundle, rumtk_web_init_api_endpoints,
30 rumtk_web_init_components, rumtk_web_init_forms, rumtk_web_init_job_manager,
31 rumtk_web_init_pages,
32};
33use crate::{rumtk_web_fetch, rumtk_web_load_conf};
34
35use rumtk_core::core::RUMResult;
36use rumtk_core::dependencies::clap;
37use rumtk_core::strings::RUMString;
38use rumtk_core::threading::threading_functions::get_default_system_thread_count;
39use rumtk_core::types::{RUMCLIParser, RUMTcpListener};
40use rumtk_core::{rumtk_init_threads, rumtk_resolve_task};
41
42use crate::api::UserAPIEndpoints;
43use axum::routing::{get, post};
44use axum::Router;
45use tower_http::compression::{CompressionLayer, DefaultPredicate};
46use tower_http::services::ServeDir;
47
48///
49/// RUMTK WebApp CLI Args
50///
51#[derive(RUMCLIParser, Debug)]
52#[command(author, version, about, long_about = None)]
53struct Args {
54 ///
55 /// Website title to use internally. It can be omitted if defined in the app.json config file
56 /// bundled with your app.
57 ///
58 #[arg(long, default_value = "")]
59 pub title: RUMString,
60 ///
61 /// Website description string. It can be omitted if defined in the app.json config file
62 /// bundled with your app.
63 ///
64 #[arg(long, default_value = "")]
65 pub description: RUMString,
66 ///
67 /// Company to display in website.
68 ///
69 #[arg(long, default_value = "")]
70 pub company: RUMString,
71 ///
72 /// Copyright year to display in website.
73 ///
74 #[arg(short, long, default_value = "")]
75 pub copyright: RUMString,
76 ///
77 /// Directory to scan on startup to find custom CSS sources to bundle into a minified CSS file
78 /// that can be quickly pulled by the app client side.
79 ///
80 /// This option can provide an alternative to direct component retrieval of CSS fragments.
81 /// Meaning, you could bundle all of your fragments into the master bundle at startup and
82 /// turn off component level ```custom_css_enabled``` option in the ```app.json``` config.
83 ///
84 #[arg(long, default_value = DEFAULT_OUT_CSS_DIR)]
85 pub css_source_dir: RUMString,
86 ///
87 /// Is the interface meant to be bound to the loopback address and remain hidden from the
88 /// outside world.
89 ///
90 /// It follows the format ```IPv4:port``` and it is a string.
91 ///
92 /// If a NIC IP is defined via `--ip`, that value will override this flag.
93 ///
94 #[arg(short, long, default_value = DEFAULT_LOCAL_LISTENING_ADDRESS)]
95 pub ip: RUMString,
96 ///
97 /// How many threads to use to serve the website. By default, we use
98 /// ```get_default_system_thread_count()``` from ```rumtk-core``` to detect the total count of
99 /// cpus available. We use the system's total count of cpus by default.
100 ///
101 #[arg(long, default_value_t = get_default_system_thread_count())]
102 pub threads: usize,
103}
104
105async fn run_app(args: &Args, skip_serve: bool) -> RUMResult<()> {
106 let state = rumtk_web_load_conf!(&args);
107 let comression_layer: CompressionLayer = CompressionLayer::new()
108 .br(true)
109 .deflate(true)
110 .gzip(true)
111 .zstd(true)
112 .compress_when(DefaultPredicate::new());
113 let app = Router::new()
114 /* Robots.txt */
115 .route("/robots.txt", get(rumtk_web_fetch!(default_robots_matcher)))
116 /* Components */
117 .route(
118 "/component/{*name}",
119 get(rumtk_web_fetch!(default_component_matcher)),
120 )
121 /* Pages */
122 .route("/", get(rumtk_web_fetch!(default_page_matcher)))
123 .route("/{*page}", get(rumtk_web_fetch!(default_page_matcher)))
124 /* Post Handling */
125 .route("/api/", post(rumtk_web_api_process!(default_api_matcher)))
126 .route(
127 "/api/{*page}",
128 post(rumtk_web_api_process!(default_api_matcher)),
129 )
130 /* Services */
131 .nest_service("/static", ServeDir::new("static"))
132 .with_state(state)
133 .layer(comression_layer);
134
135 let listener = RUMTcpListener::bind(&args.ip.as_str())
136 .await
137 .expect("There was an issue biding the listener.");
138 println!("listening on {}", listener.local_addr().unwrap());
139
140 if !skip_serve {
141 axum::serve(listener, app)
142 .await
143 .expect("There was an issue with the server.");
144 }
145
146 Ok(())
147}
148
149pub fn app_main(
150 pages: &UserPages,
151 components: &UserComponents,
152 forms: &Forms,
153 apis: &UserAPIEndpoints,
154 skip_serve: bool,
155) {
156 let args = Args::parse();
157
158 rumtk_web_init_components!(components);
159 rumtk_web_init_pages!(pages);
160 rumtk_web_init_forms!(forms);
161 rumtk_web_init_api_endpoints!(apis);
162 rumtk_web_compile_css_bundle!(&args.css_source_dir);
163
164 let rt = rumtk_init_threads!(&args.threads);
165 rumtk_web_init_job_manager!(&args.threads);
166 let task = run_app(&args, skip_serve);
167 rumtk_resolve_task!(rt, task);
168}
169
170///
171/// This is the main macro for defining your applet and launching it.
172/// Usage is very simple and the only decision from a user is whether to pass a list of
173/// [UserPages](crate::pages::UserPages) or a list of [UserPages](crate::pages::UserPages) and a list
174/// of [UserComponents](crate::components::UserComponents).
175///
176/// These lists are used to automatically register your pages
177/// (e.g. `/index => ('index', my_index_function)`) and your custom components
178/// (e.g. `button => ('button', my_button_function)`
179///
180/// This macro will load CSS from predefined sources, concatenate their contents with predefined CSS,
181/// minified the concatenated results, and generate a bundle css file containing the minified results.
182/// The CSS bundle is written to file `./static/css/bundle.min.css`.
183///
184/// ***Note: anything in ./static will be considered static assets that need to be served.***
185///
186/// This macro will also parse the command line automatically with a few predefined options and
187/// use that information to override the config defaults.
188///
189/// By default, the app is launched to `127.0.0.1:3000` which is the loopback address.
190///
191/// App is served with the best compression algorithm allowed by the client browser.
192///
193/// For testing purposes, the function
194///
195/// ## Example Usage
196///
197/// ### With Page and Component definition
198/// ```
199/// use rumtk_core::strings::{rumtk_format};
200/// use rumtk_web::{
201/// rumtk_web_run_app,
202/// rumtk_web_render_component,
203/// rumtk_web_render_html,
204/// rumtk_web_get_text_item
205/// };
206/// use rumtk_web::components::form::{FormElementBuilder, props::InputProps, FormElements};
207/// use rumtk_web::{SharedAppState, RenderedPageComponents};
208/// use rumtk_web::{APIPath, URLPath, URLParams, HTMLResult, RUMString, RouterForm, FormData, RUMWebData};
209/// use rumtk_web::defaults::{DEFAULT_TEXT_ITEM, PARAMS_CONTENTS, PARAMS_CSS_CLASS};
210/// use rumtk_web::utils::types::RUMWebTemplate;
211///
212///
213///
214///
215/// // About page
216/// pub fn about(app_state: SharedAppState) -> RenderedPageComponents {
217/// let title_coop = rumtk_web_render_component!("title", [("type", "coop_values")], app_state.clone());
218/// let title_team = rumtk_web_render_component!("title", [("type", "meet_the_team")], app_state.clone());
219///
220/// let text_card_story = rumtk_web_render_component!("text_card", [("type", "story")], app_state.clone());
221/// let text_card_coop = rumtk_web_render_component!("text_card", [("type", "coop_values")], app_state.clone());
222///
223/// let portrait_card = rumtk_web_render_component!("portrait_card", [("section", "company"), ("type", "personnel")], app_state.clone());
224///
225/// let spacer_5 = rumtk_web_render_component!("spacer", [("size", "5")], app_state.clone());
226///
227/// vec![
228/// text_card_story,
229/// spacer_5.clone(),
230/// title_coop,
231/// text_card_coop,
232/// spacer_5,
233/// title_team,
234/// portrait_card
235/// ]
236/// }
237///
238/// //Custom component
239/// #[derive(RUMWebTemplate, Debug)]
240/// #[template(
241/// source = "
242/// <style>
243///
244/// </style>
245/// {% if custom_css_enabled %}
246/// <link href='/static/components/div.css' rel='stylesheet'>
247/// {% endif %}
248/// <div class='div-{{css_class}}'>{{contents|safe}}</div>
249/// ",
250/// ext = "html"
251/// )]
252/// struct MyDiv {
253/// contents: RUMString,
254/// css_class: RUMString,
255/// custom_css_enabled: bool,
256/// }
257///
258/// fn my_div(path_components: URLPath, params: URLParams, state: SharedAppState) -> HTMLResult {
259/// let contents = rumtk_web_get_text_item!(params, PARAMS_CONTENTS, DEFAULT_TEXT_ITEM);
260/// let css_class = rumtk_web_get_text_item!(params, PARAMS_CSS_CLASS, DEFAULT_TEXT_ITEM);
261///
262/// let custom_css_enabled = state.read().expect("Lock failure").get_config().custom_css;
263///
264/// rumtk_web_render_html!(MyDiv {
265/// contents: RUMString::from(contents),
266/// css_class: RUMString::from(css_class),
267/// custom_css_enabled
268/// })
269/// }
270///
271/// fn my_form (builder: FormElementBuilder) -> FormElements {
272/// vec![
273/// builder("input", "", InputProps::default(), "default")
274/// ]
275/// }
276///
277/// fn my_api_handler(path: APIPath, params: RUMWebData, form: FormData, state: SharedAppState) -> HTMLResult {
278/// Err(rumtk_format!(
279/// "No handler registered for API endpoint => {}",
280/// path
281/// ))
282/// }
283///
284/// //Requesting to immediately exit instead of indefinitely serving pages so this example can be used as a unit test.
285/// let skip_serve = true;
286///
287/// let result = rumtk_web_run_app!(
288/// vec![("about", about)],
289/// vec![("my_div", my_div)], //Optional, can be omitted alongside the skip_serve flag
290/// vec![("my_form", my_form)], //Optional, can be omitted alongside the skip_serve flag
291/// vec![("v2/add", my_api_handler)], //Optional, can be omitted alongside the skip_serve flag
292/// skip_serve //Omit in production code. This is used so that this example can work as a unit test.
293/// );
294/// ```
295///
296#[macro_export]
297macro_rules! rumtk_web_run_app {
298 ( ) => {{
299 use $crate::utils::app::app_main;
300
301 app_main(&vec![], &vec![], &vec![], &vec![], false)
302 }};
303 ( $pages:expr ) => {{
304 use $crate::utils::app::app_main;
305
306 app_main(&$pages, &vec![], &vec![], &vec![], false)
307 }};
308 ( $pages:expr, $components:expr ) => {{
309 use $crate::utils::app::app_main;
310
311 app_main(&$pages, &$components, &vec![], &vec![], false)
312 }};
313 ( $pages:expr, $components:expr, $forms:expr ) => {{
314 use $crate::utils::app::app_main;
315
316 app_main(&$pages, &$components, &$forms, &vec![], false)
317 }};
318 ( $pages:expr, $components:expr, $forms:expr, $apis:expr ) => {{
319 use $crate::utils::app::app_main;
320
321 app_main(&$pages, &$components, &$forms, &$apis, false)
322 }};
323 ( $pages:expr, $components:expr, $forms:expr, $apis:expr, $skip_serve:expr ) => {{
324 use $crate::utils::app::app_main;
325
326 app_main(&$pages, &$components, &$forms, &$apis, $skip_serve)
327 }};
328}