Skip to main content

transitous_core/
config.rs

1//! The configuration: the file, overridden by environment variables.
2//!
3//! ```toml
4//! contact = "mailto:me@example.org"
5//! base_url = "https://api.transitous.org"
6//! timeout_seconds = 20
7//! plan_daily_limit = 720
8//! delay_threshold_minutes = 2
9//! ```
10//!
11//! The file is `config.toml` in the directory of [`dirs::config`], or the
12//! one `TRANSITOUS_CONFIG` names. `TRANSITOUS_CONTACT` and
13//! `TRANSITOUS_BASE_URL` override the file, and `TRANSITOUS_NO_CACHE` turns
14//! the cache off.
15
16use std::io;
17use std::path::{Path, PathBuf};
18use std::time::Duration;
19
20use serde::{Deserialize, Serialize};
21
22use crate::dirs;
23
24/// The public instance.
25pub const DEFAULT_BASE_URL: &str = "https://api.transitous.org";
26pub const DEFAULT_TIMEOUT_SECONDS: u64 = 20;
27/// The number of `plan` requests per 24 hours that Transitous allows without
28/// asking.
29pub const DEFAULT_PLAN_DAILY_LIMIT: u32 = 720;
30/// From how many minutes late an arrival counts as delayed.
31pub const DEFAULT_DELAY_THRESHOLD_MINUTES: u32 = 2;
32
33/// The configuration file could not be read or written, or a value is
34/// invalid.
35#[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/// The contents of the configuration file. Unset values take their default.
53#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(deny_unknown_fields)]
55pub struct Settings {
56    /// How Transitous can reach the operator: a URL, a `mailto:` URL or an
57    /// email address. Required for every request.
58    #[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    /// Raise only after agreeing on more with Transitous.
65    #[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    /// The names of the settings, as in the file.
73    pub const KEYS: &[&str] = &[
74        "contact",
75        "base_url",
76        "timeout_seconds",
77        "plan_daily_limit",
78        "delay_threshold_minutes",
79    ];
80
81    /// The file `TRANSITOUS_CONFIG` names, else `config.toml` in
82    /// [`dirs::config`]. `None` if the home directory is unknown.
83    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    /// Reads the file, or returns empty settings if it does not exist.
90    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    /// Writes the file, creating its directory if needed. Replaces the file
108    /// at once, so a failed write leaves the old one intact.
109    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        // A relative file name has an empty parent, which needs no creation.
118        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    /// The value of a setting, as text. `None` if unset.
125    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    /// Sets a setting from text, or unsets it with `None`. Checks the value.
137    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
174/// A non-empty environment variable.
175fn variable(env: &impl Fn(&str) -> Option<String>, name: &str) -> Option<String> {
176    env(name).filter(|value| !value.is_empty())
177}
178
179/// The configuration in effect.
180#[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    /// `None`: no cache.
188    pub cache_dir: Option<PathBuf>,
189    /// Where the usage counter lives. `None`: the temporary directory.
190    pub state_dir: Option<PathBuf>,
191}
192
193impl Config {
194    /// Reads the file and applies the environment variables `env` returns.
195    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    /// The settings with the environment variables `env` returns applied.
204    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}