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(section) {
115            Some(l) => match l.get(&self.lang) {
116                Some(i) => i.clone(),
117                None => match l.get(DEFAULT_TEXT_ITEM) {
118                    Some(i) => i.clone(),
119                    None => TextMap::default(),
120                },
121            },
122            None => TextMap::default(),
123        }
124    }
125}
126
127pub type ClipboardID = RUMString;
128///
129/// Main internal structure for holding the initial app configuration ([AppConf](crate::utils::AppConf)),
130/// the `clipboard` containing dynamically generated state ([NestedTextMap](crate::utils::NestedTextMap)),
131/// and the `jobs` field containing
132///
133pub struct AppState {
134    config: AppConf,
135    clipboard: NestedTextMap,
136    jobs: RUMHashMap<RUMID, Job>,
137}
138
139pub type SafeAppState = Arc<RwLock<AppState>>;
140
141impl AppState {
142    pub fn new() -> AppState {
143        AppState {
144            config: AppConf::default(),
145            clipboard: NestedTextMap::default(),
146            jobs: RUMHashMap::default(),
147        }
148    }
149
150    pub fn new_safe() -> SafeAppState {
151        Arc::new(RwLock::new(AppState::new()))
152    }
153
154    pub fn from_safe(conf: AppConf) -> SafeAppState {
155        Arc::new(RwLock::new(AppState::from(conf)))
156    }
157
158    pub fn get_config(&self) -> &AppConf {
159        &self.config
160    }
161
162    pub fn get_config_mut(&mut self) -> &mut AppConf {
163        &mut self.config
164    }
165
166    pub fn has_clipboard(&self, id: &ClipboardID) -> bool {
167        self.clipboard.contains_key(id)
168    }
169
170    pub fn has_job(&self, id: &JobID) -> bool {
171        self.jobs.contains_key(id)
172    }
173
174    pub fn push_job_result(&mut self, id: &JobID, job: Job) {
175        self.jobs.insert(id.clone(), job);
176    }
177
178    pub fn push_to_clipboard(&mut self, data: TextMap) -> ClipboardID {
179        let clipboard_id = rumtk_generate_id!().to_rumstring();
180        self.clipboard.insert(clipboard_id.clone(), data);
181        clipboard_id
182    }
183
184    pub fn request_clipboard_slice(&mut self) -> ClipboardID {
185        let clipboard_id = rumtk_generate_id!().to_rumstring();
186        self.clipboard
187            .insert(clipboard_id.clone(), TextMap::default());
188        clipboard_id
189    }
190
191    pub fn pop_job(&mut self, id: &RUMID) -> Option<Job> {
192        self.jobs.remove(id)
193    }
194
195    pub fn pop_clipboard(&mut self, id: &ClipboardID) -> Option<TextMap> {
196        self.clipboard.shift_remove(id)
197    }
198}
199
200impl From<AppConf> for AppState {
201    fn from(config: AppConf) -> Self {
202        AppState {
203            config,
204            clipboard: NestedTextMap::default(),
205            jobs: RUMHashMap::default(),
206        }
207    }
208}
209
210pub type SharedAppState = Arc<RwLock<AppState>>;
211pub type RouterAppState = State<Arc<RwLock<AppState>>>;
212
213#[macro_export]
214macro_rules! rumtk_web_load_conf {
215    ( $args:expr ) => {{
216        rumtk_web_load_conf!($args, "./app.json")
217    }};
218    ( $args:expr, $path:expr ) => {{
219        use rumtk_core::rumtk_deserialize;
220        use rumtk_core::strings::RUMStringConversions;
221        use rumtk_core::types::RUMHashMap;
222        use std::fs;
223
224        use $crate::rumtk_web_save_conf;
225        use $crate::utils::{AppConf, AppState, TextMap};
226
227        let json = match fs::read_to_string($path) {
228            Ok(json) => json,
229            Err(err) => rumtk_web_save_conf!($path),
230        };
231
232        let mut conf: AppConf = match rumtk_deserialize!(json) {
233            Ok(conf) => conf,
234            Err(err) => panic!(
235                "The App config file in {} does not meet the expected structure. \
236                    See the documentation for more information. Error: {}\n{}",
237                $path, err, json
238            ),
239        };
240        conf.update_site_info(
241            $args.title.clone(),
242            $args.description.clone(),
243            $args.company.clone(),
244            $args.copyright.clone(),
245        );
246        AppState::from_safe(conf)
247    }};
248}
249
250#[macro_export]
251macro_rules! rumtk_web_save_conf {
252    ( $path:expr ) => {{
253        use rumtk_core::rumtk_serialize;
254        use rumtk_core::strings::RUMStringConversions;
255        use std::fs;
256        use $crate::utils::AppConf;
257
258        let json = rumtk_serialize!(AppConf::default(), true)?;
259        fs::write($path, &json);
260        json
261    }};
262}
263
264#[macro_export]
265macro_rules! rumtk_web_get_string {
266    ( $conf:expr, $item:expr ) => {{
267        let owned_state = $conf.read().expect("Lock failure");
268        owned_state.get_config().get_text($item)
269    }};
270}
271
272#[macro_export]
273macro_rules! rumtk_web_get_conf {
274    ( $conf:expr, $item:expr ) => {{
275        let owned_state = $conf.read().expect("Lock failure");
276        owned_state.get_config().get_conf($item)
277    }};
278}
279
280/*
281   Default non static data to minimize allocations.
282*/
283pub const DEFAULT_TEXT: fn() -> RUMString = || RUMString::default();
284pub const DEFAULT_TEXTMAP: fn() -> TextMap = || TextMap::default();
285pub const DEFAULT_NESTEDTEXTMAP: fn() -> NestedTextMap = || NestedTextMap::default();
286pub const DEFAULT_NESTEDNESTEDTEXTMAP: fn() -> NestedNestedTextMap =
287    || NestedNestedTextMap::default();