1use std::io;
17use std::path::{Path, PathBuf};
18use std::time::Duration;
19
20use serde::{Deserialize, Serialize};
21
22use crate::dirs;
23
24pub const DEFAULT_BASE_URL: &str = "https://api.transitous.org";
26pub const DEFAULT_TIMEOUT_SECONDS: u64 = 20;
27pub const DEFAULT_PLAN_DAILY_LIMIT: u32 = 720;
30pub const DEFAULT_DELAY_THRESHOLD_MINUTES: u32 = 2;
32
33#[derive(Debug, thiserror::Error)]
36pub enum Error {
37 #[error("cannot read {}", path.display())]
38 Read { path: PathBuf, source: io::Error },
39 #[error("{} is not a valid configuration", path.display())]
40 Parse {
41 path: PathBuf,
42 source: toml::de::Error,
43 },
44 #[error("cannot write {}", path.display())]
45 Write { path: PathBuf, source: io::Error },
46 #[error("unknown setting {0}, known are: {keys}", keys = Settings::KEYS.join(", "))]
47 UnknownKey(String),
48 #[error("invalid value for {key}: {reason}")]
49 InvalidValue { key: String, reason: String },
50}
51
52#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(deny_unknown_fields)]
55pub struct Settings {
56 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub contact: Option<String>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pub base_url: Option<String>,
62 #[serde(default, skip_serializing_if = "Option::is_none")]
63 pub timeout_seconds: Option<u64>,
64 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub plan_daily_limit: Option<u32>,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub delay_threshold_minutes: Option<u32>,
69}
70
71impl Settings {
72 pub const KEYS: &[&str] = &[
74 "contact",
75 "base_url",
76 "timeout_seconds",
77 "plan_daily_limit",
78 "delay_threshold_minutes",
79 ];
80
81 pub fn path(env: &impl Fn(&str) -> Option<String>) -> Option<PathBuf> {
84 variable(env, "TRANSITOUS_CONFIG")
85 .map(PathBuf::from)
86 .or_else(|| dirs::config().map(|dir| dir.join("config.toml")))
87 }
88
89 pub fn load(path: &Path) -> Result<Self, Error> {
91 let text = match std::fs::read_to_string(path) {
92 Ok(text) => text,
93 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()),
94 Err(source) => {
95 return Err(Error::Read {
96 path: path.to_owned(),
97 source,
98 });
99 }
100 };
101 toml::from_str(&text).map_err(|source| Error::Parse {
102 path: path.to_owned(),
103 source,
104 })
105 }
106
107 pub fn save(&self, path: &Path) -> Result<(), Error> {
110 let write = |source| Error::Write {
111 path: path.to_owned(),
112 source,
113 };
114 let text = toml::to_string(self)
115 .map_err(io::Error::other)
116 .map_err(write)?;
117 std::fs::create_dir_all(path.parent().unwrap_or(Path::new(""))).map_err(write)?;
119 let temporary = path.with_extension("toml.tmp");
120 std::fs::write(&temporary, text).map_err(write)?;
121 std::fs::rename(&temporary, path).map_err(write)
122 }
123
124 pub fn get(&self, key: &str) -> Result<Option<String>, Error> {
126 Ok(match key {
127 "contact" => self.contact.clone(),
128 "base_url" => self.base_url.clone(),
129 "timeout_seconds" => self.timeout_seconds.map(|v| v.to_string()),
130 "plan_daily_limit" => self.plan_daily_limit.map(|v| v.to_string()),
131 "delay_threshold_minutes" => self.delay_threshold_minutes.map(|v| v.to_string()),
132 _ => return Err(Error::UnknownKey(key.to_owned())),
133 })
134 }
135
136 pub fn set(&mut self, key: &str, value: Option<&str>) -> Result<(), Error> {
138 let invalid = |reason: String| Error::InvalidValue {
139 key: key.to_owned(),
140 reason,
141 };
142 match key {
143 "contact" => {
144 if let Some(contact) = value {
145 crate::agent::check_contact(contact).map_err(|e| invalid(e.to_string()))?;
146 }
147 self.contact = value.map(str::to_owned);
148 }
149 "base_url" => {
150 if let Some(url) = value {
151 motis::Url::parse(url).map_err(|e| invalid(e.to_string()))?;
152 }
153 self.base_url = value.map(str::to_owned);
154 }
155 "timeout_seconds" => self.timeout_seconds = number(value).map_err(invalid)?,
156 "plan_daily_limit" => self.plan_daily_limit = number(value).map_err(invalid)?,
157 "delay_threshold_minutes" => {
158 self.delay_threshold_minutes = number(value).map_err(invalid)?;
159 }
160 _ => return Err(Error::UnknownKey(key.to_owned())),
161 }
162 Ok(())
163 }
164}
165
166fn number<T: std::str::FromStr<Err: std::fmt::Display>>(
167 value: Option<&str>,
168) -> Result<Option<T>, String> {
169 value
170 .map(|v| v.parse().map_err(|e| format!("{e}")))
171 .transpose()
172}
173
174fn variable(env: &impl Fn(&str) -> Option<String>, name: &str) -> Option<String> {
176 env(name).filter(|value| !value.is_empty())
177}
178
179#[derive(Debug, Clone, PartialEq, Eq)]
181pub struct Config {
182 pub contact: Option<String>,
183 pub base_url: String,
184 pub timeout: Duration,
185 pub plan_daily_limit: u32,
186 pub delay_threshold_minutes: u32,
187 pub cache_dir: Option<PathBuf>,
189 pub state_dir: Option<PathBuf>,
191}
192
193impl Config {
194 pub fn load(env: &impl Fn(&str) -> Option<String>) -> Result<Self, Error> {
196 let settings = Settings::path(env)
197 .map(|path| Settings::load(&path))
198 .transpose()?
199 .unwrap_or_default();
200 Ok(Self::new(settings, env))
201 }
202
203 pub fn new(settings: Settings, env: &impl Fn(&str) -> Option<String>) -> Self {
205 let no_cache = variable(env, "TRANSITOUS_NO_CACHE")
206 .is_some_and(|value| !matches!(value.as_str(), "0" | "false"));
207 Self {
208 contact: variable(env, "TRANSITOUS_CONTACT").or(settings.contact),
209 base_url: variable(env, "TRANSITOUS_BASE_URL")
210 .or(settings.base_url)
211 .unwrap_or_else(|| DEFAULT_BASE_URL.to_owned()),
212 timeout: Duration::from_secs(
213 settings.timeout_seconds.unwrap_or(DEFAULT_TIMEOUT_SECONDS),
214 ),
215 plan_daily_limit: settings
216 .plan_daily_limit
217 .unwrap_or(DEFAULT_PLAN_DAILY_LIMIT),
218 delay_threshold_minutes: settings
219 .delay_threshold_minutes
220 .unwrap_or(DEFAULT_DELAY_THRESHOLD_MINUTES),
221 cache_dir: if no_cache { None } else { dirs::cache() },
222 state_dir: dirs::state(),
223 }
224 }
225}