Skip to main content

rumtk_web/utils/
conf.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::jobs::{Job, JobID};
24use crate::utils::defaults::DEFAULT_TEXT_ITEM;
25use crate::utils::types::RUMString;
26use axum::extract::State;
27use phf::OrderedMap;
28pub use phf_macros::phf_ordered_map as rumtk_create_const_ordered_map;
29use rumtk_core::rumtk_generate_id;
30use rumtk_core::strings::RUMStringConversions;
31use rumtk_core::types::{RUMDeserialize, RUMDeserializer, RUMSerialize, RUMSerializer, RUMID};
32use rumtk_core::types::{RUMHashMap, RUMOrderedMap};
33use std::sync::{Arc, RwLock};
34
35pub type TextMap = RUMOrderedMap<RUMString, RUMString>;
36pub type NestedTextMap = RUMOrderedMap<RUMString, TextMap>;
37pub type NestedNestedTextMap = RUMOrderedMap<RUMString, NestedTextMap>;
38pub type RootNestedNestedTextMap = RUMOrderedMap<RUMString, NestedNestedTextMap>;
39
40pub type ConstTextMap = OrderedMap<&'static str, &'static str>;
41pub type ConstNestedTextMap = OrderedMap<&'static str, &'static ConstTextMap>;
42pub type ConstNestedNestedTextMap = OrderedMap<&'static str, &'static ConstNestedTextMap>;
43
44#[derive(RUMSerialize, RUMDeserialize, PartialEq, Debug, Clone, Default)]
45pub struct HeaderConf {
46    pub logo_size: RUMString,
47    pub disable_navlinks: bool,
48    pub disable_logo: bool,
49}
50
51#[derive(RUMSerialize, RUMDeserialize, PartialEq, Debug, Clone, Default)]
52pub struct FooterConf {
53    pub socials_list: RUMString,
54    pub disable_contact_button: bool,
55}
56
57///
58/// This is a core structure in a web project using the RUMTK framework. This structure contains
59/// a series of fields that represent the web app initial state or configuration. The idea is that
60/// the web app can come bundled with a JSON config file following this structure which we can load
61/// at runtime. The settings will dictate a few key project behaviors such as properly labeling
62/// some components with the company name or use the correct language text.
63///
64#[derive(RUMSerialize, RUMDeserialize, PartialEq, Debug, Clone, Default)]
65pub struct AppConf {
66    pub title: RUMString,
67    pub description: RUMString,
68    pub company: RUMString,
69    pub copyright: RUMString,
70    pub lang: RUMString,
71    pub theme: RUMString,
72    pub custom_css: bool,
73    pub header_conf: HeaderConf,
74    pub footer_conf: FooterConf,
75
76    strings: RootNestedNestedTextMap,
77    config: NestedNestedTextMap,
78    //pub opts: TextMap,
79}
80
81impl AppConf {
82    pub fn update_site_info(
83        &mut self,
84        title: RUMString,
85        description: RUMString,
86        company: RUMString,
87        copyright: RUMString,
88    ) {
89        if !title.is_empty() {
90            self.title = title;
91        }
92        if !company.is_empty() {
93            self.company = company;
94        }
95        if !description.is_empty() {
96            self.description = description;
97        }
98        if !copyright.is_empty() {
99            self.copyright = copyright;
100        }
101    }
102
103    pub fn get_text(&self, item: &str) -> NestedTextMap {
104        match self.strings.get(&self.lang) {
105            Some(l) => match l.get(item) {
106                Some(i) => i.clone(),
107                None => NestedTextMap::default(),
108            },
109            None => NestedTextMap::default(),
110        }
111    }
112
113    pub fn get_conf(&self, section: &str) -> TextMap {
114        match self.config.get(&self.lang) {
115            Some(l) => match l.get(section) {
116                Some(i) => i.clone(),
117                None => TextMap::default(),
118            },
119            None => match self.config.get(DEFAULT_TEXT_ITEM) {
120                Some(l) => match l.get(section) {
121                    Some(i) => i.clone(),
122                    None => TextMap::default(),
123                },
124                None => TextMap::default(),
125            },
126        }
127    }
128}
129
130pub type ClipboardID = RUMString;
131///
132/// Main internal structure for holding the initial app configuration ([AppConf](crate::utils::AppConf)),
133/// the `clipboard` containing dynamically generated state ([NestedTextMap](crate::utils::NestedTextMap)),
134/// and the `jobs` field containing
135///
136pub struct AppState {
137    config: AppConf,
138    clipboard: NestedTextMap,
139    jobs: RUMHashMap<RUMID, Job>,
140}
141
142pub type SafeAppState = Arc<RwLock<AppState>>;
143
144impl AppState {
145    pub fn new() -> AppState {
146        AppState {
147            config: AppConf::default(),
148            clipboard: NestedTextMap::default(),
149            jobs: RUMHashMap::default(),
150        }
151    }
152
153    pub fn new_safe() -> SafeAppState {
154        Arc::new(RwLock::new(AppState::new()))
155    }
156
157    pub fn from_safe(conf: AppConf) -> SafeAppState {
158        Arc::new(RwLock::new(AppState::from(conf)))
159    }
160
161    pub fn get_config(&self) -> &AppConf {
162        &self.config
163    }
164
165    pub fn get_config_mut(&mut self) -> &mut AppConf {
166        &mut self.config
167    }
168
169    pub fn has_clipboard(&self, id: &ClipboardID) -> bool {
170        self.clipboard.contains_key(id)
171    }
172
173    pub fn has_job(&self, id: &JobID) -> bool {
174        self.jobs.contains_key(id)
175    }
176
177    pub fn push_job_result(&mut self, id: &JobID, job: Job) {
178        self.jobs.insert(id.clone(), job);
179    }
180
181    pub fn push_to_clipboard(&mut self, data: TextMap) -> ClipboardID {
182        let clipboard_id = rumtk_generate_id!().to_rumstring();
183        self.clipboard.insert(clipboard_id.clone(), data);
184        clipboard_id
185    }
186
187    pub fn request_clipboard_slice(&mut self) -> ClipboardID {
188        let clipboard_id = rumtk_generate_id!().to_rumstring();
189        self.clipboard
190            .insert(clipboard_id.clone(), TextMap::default());
191        clipboard_id
192    }
193
194    pub fn pop_job(&mut self, id: &RUMID) -> Option<Job> {
195        self.jobs.remove(id)
196    }
197
198    pub fn pop_clipboard(&mut self, id: &ClipboardID) -> Option<TextMap> {
199        self.clipboard.shift_remove(id)
200    }
201}
202
203impl From<AppConf> for AppState {
204    fn from(config: AppConf) -> Self {
205        AppState {
206            config,
207            clipboard: NestedTextMap::default(),
208            jobs: RUMHashMap::default(),
209        }
210    }
211}
212
213pub type SharedAppState = Arc<RwLock<AppState>>;
214pub type RouterAppState = State<Arc<RwLock<AppState>>>;
215
216#[macro_export]
217macro_rules! rumtk_web_load_conf {
218    ( $args:expr ) => {{
219        rumtk_web_load_conf!($args, "./app.json")
220    }};
221    ( $args:expr, $path:expr ) => {{
222        use rumtk_core::rumtk_deserialize;
223        use rumtk_core::strings::RUMStringConversions;
224        use rumtk_core::types::RUMHashMap;
225        use std::fs;
226
227        use $crate::rumtk_web_save_conf;
228        use $crate::utils::{AppConf, AppState, TextMap};
229
230        let json = match fs::read_to_string($path) {
231            Ok(json) => json,
232            Err(err) => rumtk_web_save_conf!($path),
233        };
234
235        let mut conf: AppConf = match rumtk_deserialize!(json) {
236            Ok(conf) => conf,
237            Err(err) => panic!(
238                "The App config file in {} does not meet the expected structure. \
239                    See the documentation for more information. Error: {}\n{}",
240                $path, err, json
241            ),
242        };
243        conf.update_site_info(
244            $args.title.clone(),
245            $args.description.clone(),
246            $args.company.clone(),
247            $args.copyright.clone(),
248        );
249        AppState::from_safe(conf)
250    }};
251}
252
253#[macro_export]
254macro_rules! rumtk_web_save_conf {
255    ( $path:expr ) => {{
256        use rumtk_core::rumtk_serialize;
257        use rumtk_core::strings::RUMStringConversions;
258        use std::fs;
259        use $crate::utils::AppConf;
260
261        let json = rumtk_serialize!(AppConf::default(), true)?;
262        fs::write($path, &json);
263        json
264    }};
265}
266
267#[macro_export]
268macro_rules! rumtk_web_get_string {
269    ( $conf:expr, $item:expr ) => {{
270        let owned_state = $conf.read().expect("Lock failure");
271        owned_state.get_config().get_text($item)
272    }};
273}
274
275#[macro_export]
276macro_rules! rumtk_web_get_conf {
277    ( $conf:expr, $item:expr ) => {{
278        let owned_state = $conf.read().expect("Lock failure");
279        owned_state.get_config().get_conf($item)
280    }};
281}
282
283/*
284   Default non static data to minimize allocations.
285*/
286pub const DEFAULT_TEXT: fn() -> RUMString = || RUMString::default();
287pub const DEFAULT_TEXTMAP: fn() -> TextMap = || TextMap::default();
288pub const DEFAULT_NESTEDTEXTMAP: fn() -> NestedTextMap = || NestedTextMap::default();
289pub const DEFAULT_NESTEDNESTEDTEXTMAP: fn() -> NestedNestedTextMap =
290    || NestedNestedTextMap::default();