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_compile_css_bundle, rumtk_web_init_components, rumtk_web_init_forms,
30 rumtk_web_init_pages, rumtk_web_post,
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 axum::routing::{get, post};
42use axum::Router;
43use tower_http::compression::{CompressionLayer, DefaultPredicate};
44use tower_http::services::ServeDir;
45use tracing::error;
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_post!(default_page_matcher)))
125 .route("/api/{*page}", post(rumtk_web_post!(default_page_matcher)))
126 /* Services */
127 .nest_service("/static", ServeDir::new("static"))
128 .with_state(state)
129 .layer(comression_layer);
130
131 let listener = RUMTcpListener::bind(&args.ip.as_str())
132 .await
133 .expect("There was an issue biding the listener.");
134 println!("listening on {}", listener.local_addr().unwrap());
135
136 if !skip_serve {
137 axum::serve(listener, app)
138 .await
139 .expect("There was an issue with the server.");
140 }
141
142 Ok(())
143}
144
145pub fn app_main(pages: &UserPages, components: &UserComponents, forms: &Forms, skip_serve: bool) {
146 let args = Args::parse();
147
148 rumtk_web_init_components!(components);
149 rumtk_web_init_pages!(pages);
150 rumtk_web_init_forms!(forms);
151 rumtk_web_compile_css_bundle!(&args.css_source_dir);
152
153 let rt = rumtk_init_threads!(&args.threads);
154 let task = run_app(&args, skip_serve);
155 rumtk_resolve_task!(rt, task);
156}
157
158///
159/// This is the main macro for defining your applet and launching it.
160/// Usage is very simple and the only decision from a user is whether to pass a list of
161/// [UserPages](crate::pages::UserPages) or a list of [UserPages](crate::pages::UserPages) and a list
162/// of [UserComponents](crate::components::UserComponents).
163///
164/// These lists are used to automatically register your pages
165/// (e.g. `/index => ('index', my_index_function)`) and your custom components
166/// (e.g. `button => ('button', my_button_function)`
167///
168/// This macro will load CSS from predefined sources, concatenate their contents with predefined CSS,
169/// minified the concatenated results, and generate a bundle css file containing the minified results.
170/// The CSS bundle is written to file `./static/css/bundle.min.css`.
171///
172/// ***Note: anything in ./static will be considered static assets that need to be served.***
173///
174/// This macro will also parse the command line automatically with a few predefined options and
175/// use that information to override the config defaults.
176///
177/// By default, the app is launched to `127.0.0.1:3000` which is the loopback address.
178///
179/// App is served with the best compression algorithm allowed by the client browser.
180///
181/// For testing purposes, the function
182///
183/// ## Example Usage
184///
185/// ### With Page and Component definition
186/// ```
187/// use rumtk_web::{
188/// rumtk_web_run_app,
189/// rumtk_web_render_component,
190/// rumtk_web_render_html,
191/// rumtk_web_get_text_item
192/// };
193/// use rumtk_web::components::form::{FormElementBuilder, props::InputProps, FormElements};
194/// use rumtk_web::{SharedAppState, RenderedPageComponents};
195/// use rumtk_web::{URLPath, URLParams, HTMLResult, RUMString};
196/// use rumtk_web::defaults::{DEFAULT_TEXT_ITEM, PARAMS_CONTENTS, PARAMS_CSS_CLASS};
197///
198/// use askama::Template;
199///
200///
201///
202/// // About page
203/// pub fn about(app_state: SharedAppState) -> RenderedPageComponents {
204/// let title_coop = rumtk_web_render_component!("title", [("type", "coop_values")], app_state.clone());
205/// let title_team = rumtk_web_render_component!("title", [("type", "meet_the_team")], app_state.clone());
206///
207/// let text_card_story = rumtk_web_render_component!("text_card", [("type", "story")], app_state.clone());
208/// let text_card_coop = rumtk_web_render_component!("text_card", [("type", "coop_values")], app_state.clone());
209///
210/// let portrait_card = rumtk_web_render_component!("portrait_card", [("section", "company"), ("type", "personnel")], app_state.clone());
211///
212/// let spacer_5 = rumtk_web_render_component!("spacer", [("size", "5")], app_state.clone());
213///
214/// vec![
215/// text_card_story,
216/// spacer_5.clone(),
217/// title_coop,
218/// text_card_coop,
219/// spacer_5,
220/// title_team,
221/// portrait_card
222/// ]
223/// }
224///
225/// //Custom component
226/// #[derive(Template, Debug)]
227/// #[template(
228/// source = "
229/// <style>
230///
231/// </style>
232/// {% if custom_css_enabled %}
233/// <link href='/static/components/div.css' rel='stylesheet'>
234/// {% endif %}
235/// <div class='div-{{css_class}}'>{{contents|safe}}</div>
236/// ",
237/// ext = "html"
238/// )]
239/// struct MyDiv {
240/// contents: RUMString,
241/// css_class: RUMString,
242/// custom_css_enabled: bool,
243/// }
244///
245/// fn my_div(path_components: URLPath, params: URLParams, state: SharedAppState) -> HTMLResult {
246/// let contents = rumtk_web_get_text_item!(params, PARAMS_CONTENTS, DEFAULT_TEXT_ITEM);
247/// let css_class = rumtk_web_get_text_item!(params, PARAMS_CSS_CLASS, DEFAULT_TEXT_ITEM);
248///
249/// let custom_css_enabled = state.read().expect("Lock failure").config.custom_css;
250///
251/// rumtk_web_render_html!(MyDiv {
252/// contents: RUMString::from(contents),
253/// css_class: RUMString::from(css_class),
254/// custom_css_enabled
255/// })
256/// }
257///
258/// fn my_form (builder: FormElementBuilder) -> FormElements {
259/// vec![
260/// builder("input", "", InputProps::default(), "default")
261/// ]
262/// }
263///
264/// //Requesting to immediately exit instead of indefinitely serving pages so this example can be used as a unit test.
265/// let skip_serve = true;
266///
267/// let result = rumtk_web_run_app!(
268/// vec![("about", about)],
269/// vec![("my_div", my_div)], //Optional, can be omitted alongside the skip_serve flag
270/// vec![("my_form", my_form)], //Optional, can be omitted alongside the skip_serve flag
271/// skip_serve //Omit in production code. This is used so that this example can work as a unit test.
272/// );
273/// ```
274///
275#[macro_export]
276macro_rules! rumtk_web_run_app {
277 ( ) => {{
278 use $crate::utils::app::app_main;
279
280 app_main(&vec![], &vec![], &vec![], false)
281 }};
282 ( $pages:expr ) => {{
283 use $crate::utils::app::app_main;
284
285 app_main(&$pages, &vec![], &vec![], false)
286 }};
287 ( $pages:expr, $components:expr ) => {{
288 use $crate::utils::app::app_main;
289
290 app_main(&$pages, &$components, &vec![], false)
291 }};
292 ( $pages:expr, $components:expr, $forms:expr ) => {{
293 use $crate::utils::app::app_main;
294
295 app_main(&$pages, &$components, &$forms, false)
296 }};
297 ( $pages:expr, $components:expr, $forms:expr, $skip_serve:expr ) => {{
298 use $crate::utils::app::app_main;
299
300 app_main(&$pages, &$components, &$forms, $skip_serve)
301 }};
302}