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