1use std::fmt;
19use std::io;
20use std::path::{Path, PathBuf};
21use std::time::Duration;
22
23use serde::{Deserialize, Serialize};
24
25use crate::dirs;
26
27pub use hafas::REDACTED;
28
29pub const DEFAULT_BASE_URL: &str = "https://www.rmv.de/hapi/";
31pub const DEFAULT_TIMEOUT_SECONDS: u64 = 20;
32pub const DEFAULT_RETRIES: u32 = 2;
34pub const MAX_RETRIES: u32 = 5;
37pub const DEFAULT_DELAY_THRESHOLD_MINUTES: u32 = 2;
39
40#[derive(Debug, thiserror::Error)]
43pub enum Error {
44 #[error("cannot read {}", path.display())]
45 Read { path: PathBuf, source: io::Error },
46 #[error("{} is not a valid configuration", path.display())]
49 Parse { path: PathBuf },
50 #[error("cannot write {}", path.display())]
51 Write { path: PathBuf, source: io::Error },
52 #[error("unknown setting {0}, known are: {keys}", keys = Settings::KEYS.join(", "))]
53 UnknownKey(String),
54 #[error("invalid value for {key}: {reason}")]
55 InvalidValue { key: String, reason: String },
56}
57
58#[derive(Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
60#[serde(deny_unknown_fields)]
61pub struct Settings {
62 #[serde(default, skip_serializing_if = "Option::is_none")]
64 pub access_id: Option<String>,
65 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub base_url: Option<String>,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub timeout_seconds: Option<u64>,
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub retries: Option<u32>,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub delay_threshold_minutes: Option<u32>,
73}
74
75impl fmt::Debug for Settings {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 f.debug_struct("Settings")
78 .field("access_id", &self.access_id.as_ref().map(|_| REDACTED))
79 .field("base_url", &self.base_url)
80 .field("timeout_seconds", &self.timeout_seconds)
81 .field("retries", &self.retries)
82 .field("delay_threshold_minutes", &self.delay_threshold_minutes)
83 .finish()
84 }
85}
86
87impl Settings {
88 pub const KEYS: &[&str] = &[
90 "access_id",
91 "base_url",
92 "timeout_seconds",
93 "retries",
94 "delay_threshold_minutes",
95 ];
96
97 pub fn path(env: &impl Fn(&str) -> Option<String>) -> Option<PathBuf> {
100 variable(env, "RMV_CONFIG")
101 .map(PathBuf::from)
102 .or_else(|| dirs::config().map(|dir| dir.join("config.toml")))
103 }
104
105 pub fn load(path: &Path) -> Result<Self, Error> {
107 let text = match std::fs::read_to_string(path) {
108 Ok(text) => text,
109 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()),
110 Err(source) => {
111 return Err(Error::Read {
112 path: path.to_owned(),
113 source,
114 });
115 }
116 };
117 toml::from_str(&text).map_err(|_| Error::Parse {
118 path: path.to_owned(),
119 })
120 }
121
122 pub fn save(&self, path: &Path) -> Result<(), Error> {
126 let write = |source| Error::Write {
127 path: path.to_owned(),
128 source,
129 };
130 let text = toml::to_string(self)
131 .map_err(io::Error::other)
132 .map_err(write)?;
133 std::fs::create_dir_all(path.parent().unwrap_or(Path::new(""))).map_err(write)?;
135 let temporary = path.with_extension("toml.tmp");
136 write_private(&temporary, &text).map_err(write)?;
137 std::fs::rename(&temporary, path).map_err(write)
138 }
139
140 pub fn get(&self, key: &str) -> Result<Option<String>, Error> {
143 Ok(match key {
144 "access_id" => self.access_id.as_ref().map(|_| REDACTED.to_owned()),
145 "base_url" => self.base_url.clone(),
146 "timeout_seconds" => self.timeout_seconds.map(|v| v.to_string()),
147 "retries" => self.retries.map(|v| v.to_string()),
148 "delay_threshold_minutes" => self.delay_threshold_minutes.map(|v| v.to_string()),
149 _ => return Err(Error::UnknownKey(key.to_owned())),
150 })
151 }
152
153 pub fn set(&mut self, key: &str, value: Option<&str>) -> Result<(), Error> {
155 let invalid = |reason: String| Error::InvalidValue {
156 key: key.to_owned(),
157 reason,
158 };
159 match key {
160 "access_id" => {
161 let value = value.map(str::trim);
162 if let Some(id) = value {
163 check_access_id(id).map_err(|reason| invalid(reason.to_owned()))?;
164 }
165 self.access_id = value.map(str::to_owned);
166 }
167 "base_url" => {
168 if let Some(url) = value {
169 check_base_url(url).map_err(invalid)?;
170 }
171 self.base_url = value.map(str::to_owned);
172 }
173 "timeout_seconds" => {
174 let seconds: Option<u64> = number(value).map_err(invalid)?;
175 if seconds == Some(0) {
176 return Err(invalid("must be at least 1".to_owned()));
177 }
178 self.timeout_seconds = seconds;
179 }
180 "retries" => {
181 let retries: Option<u32> = number(value).map_err(invalid)?;
182 if retries.is_some_and(|n| n > MAX_RETRIES) {
183 return Err(invalid(format!("must be at most {MAX_RETRIES}")));
184 }
185 self.retries = retries;
186 }
187 "delay_threshold_minutes" => {
188 self.delay_threshold_minutes = number(value).map_err(invalid)?;
189 }
190 _ => return Err(Error::UnknownKey(key.to_owned())),
191 }
192 Ok(())
193 }
194}
195
196fn check_access_id(id: &str) -> Result<(), &'static str> {
198 if id.is_empty() {
199 return Err("must not be empty");
200 }
201 if id.chars().any(|c| c.is_whitespace() || c.is_control()) {
202 return Err("must not contain spaces or control characters");
203 }
204 Ok(())
205}
206
207fn check_base_url(url: &str) -> Result<(), String> {
208 let parsed = hafas::Url::parse(url).map_err(|e| e.to_string())?;
209 if matches!(parsed.scheme(), "http" | "https") {
210 Ok(())
211 } else {
212 Err("expected an http or https URL".to_owned())
213 }
214}
215
216#[cfg(unix)]
217fn write_private(path: &Path, text: &str) -> io::Result<()> {
218 use std::io::Write;
219 use std::os::unix::fs::OpenOptionsExt;
220 if let Err(error) = std::fs::remove_file(path)
222 && error.kind() != io::ErrorKind::NotFound
223 {
224 return Err(error);
225 }
226 let mut file = std::fs::OpenOptions::new()
227 .write(true)
228 .create(true)
229 .truncate(true)
230 .mode(0o600)
231 .open(path)?;
232 file.write_all(text.as_bytes())
233}
234
235#[cfg(not(unix))]
236fn write_private(path: &Path, text: &str) -> io::Result<()> {
237 std::fs::write(path, text)
238}
239
240fn number<T: std::str::FromStr<Err: fmt::Display>>(
241 value: Option<&str>,
242) -> Result<Option<T>, String> {
243 value
244 .map(|v| v.parse().map_err(|e| format!("{e}")))
245 .transpose()
246}
247
248fn variable(env: &impl Fn(&str) -> Option<String>, name: &str) -> Option<String> {
250 env(name).filter(|value| !value.trim().is_empty())
251}
252
253#[derive(Clone, PartialEq, Eq)]
255pub struct Config {
256 pub access_id: Option<String>,
257 pub base_url: String,
258 pub timeout: Duration,
259 pub retries: u32,
260 pub delay_threshold_minutes: u32,
261}
262
263impl fmt::Debug for Config {
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 f.debug_struct("Config")
266 .field("access_id", &self.access_id.as_ref().map(|_| REDACTED))
267 .field("base_url", &self.base_url)
268 .field("timeout", &self.timeout)
269 .field("retries", &self.retries)
270 .field("delay_threshold_minutes", &self.delay_threshold_minutes)
271 .finish()
272 }
273}
274
275impl Config {
276 pub fn load(env: &impl Fn(&str) -> Option<String>) -> Result<Self, Error> {
278 let settings = Settings::path(env)
279 .map(|path| Settings::load(&path))
280 .transpose()?
281 .unwrap_or_default();
282 Ok(Self::new(settings, env))
283 }
284
285 pub fn new(settings: Settings, env: &impl Fn(&str) -> Option<String>) -> Self {
287 Self {
288 access_id: variable(env, "RMV_ACCESS_ID")
289 .map(|id| id.trim().to_owned())
290 .or(settings.access_id),
291 base_url: variable(env, "RMV_BASE_URL")
292 .or(settings.base_url)
293 .unwrap_or_else(|| DEFAULT_BASE_URL.to_owned()),
294 timeout: Duration::from_secs(
295 settings
296 .timeout_seconds
297 .unwrap_or(DEFAULT_TIMEOUT_SECONDS)
298 .max(1),
299 ),
300 retries: settings.retries.unwrap_or(DEFAULT_RETRIES).min(MAX_RETRIES),
301 delay_threshold_minutes: settings
302 .delay_threshold_minutes
303 .unwrap_or(DEFAULT_DELAY_THRESHOLD_MINUTES),
304 }
305 }
306}