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