Skip to main content

acts_next/
config.rs

1use serde::Deserialize;
2use std::path::Path;
3use toml::Table;
4
5#[derive(Debug, Clone)]
6pub struct Config {
7    pub data: ConfigData,
8    pub table: Table,
9}
10
11#[derive(Debug, Clone, Deserialize)]
12pub struct ConfigLog {
13    pub dir: String,
14    pub level: String,
15}
16
17#[derive(Debug, Clone, Default, Deserialize)]
18pub struct ConfigData {
19    pub cache_cap: Option<i64>,
20    pub tick_interval_secs: Option<i64>,
21
22    // will delete message after the max retries
23    // cancel the settings by setting to 0
24    pub max_message_retry_times: Option<i32>,
25    // do not remove process and tasks on complete
26    pub keep_processes: Option<bool>,
27
28    // log config
29    pub log: Option<ConfigLog>,
30}
31
32impl Default for Config {
33    fn default() -> Self {
34        Self {
35            data: ConfigData::default(),
36            table: Table::new(),
37        }
38    }
39}
40
41impl Config {
42    pub fn create(path: &Path) -> Self {
43        #[allow(clippy::expect_fun_call)]
44        let data =
45            std::fs::read_to_string(path).expect(&format!("failed to load config file {:?}", path));
46
47        #[allow(clippy::expect_fun_call)]
48        let table = toml::from_str::<Table>(data.as_str())
49            .expect(&format!("failed to parse the toml file({:?})", path));
50
51        let data = ConfigData::deserialize(table.clone()).unwrap();
52        Self {
53            table: table.clone(),
54            data,
55        }
56    }
57
58    pub fn get<'de, T>(&self, name: &str) -> crate::Result<T>
59    where
60        T: Deserialize<'de>,
61    {
62        let value = self.table[name].clone();
63        T::deserialize(value).map_err(|err| {
64            crate::ActError::Config(format!("failed to get '{}' config: {}", name, err))
65        })
66    }
67
68    pub fn has(&self, name: &str) -> bool {
69        self.table.contains_key(name)
70    }
71
72    pub fn cache_cap(&self) -> i64 {
73        self.data.cache_cap.unwrap_or(1024)
74    }
75    pub fn keep_processes(&self) -> bool {
76        self.data.keep_processes.unwrap_or(false)
77    }
78    pub fn max_message_retry_times(&self) -> i32 {
79        self.data.max_message_retry_times.unwrap_or(20)
80    }
81    pub fn tick_interval_secs(&self) -> i64 {
82        self.data.tick_interval_secs.unwrap_or(15)
83    }
84
85    pub fn log(&self) -> ConfigLog {
86        self.data.log.clone().unwrap_or(ConfigLog {
87            dir: "log".to_string(),
88            level: "INFO".to_string(),
89        })
90    }
91}