Skip to main content

rushls_common/config/
values.rs

1//! Value shapes shared by application schemas.
2//!
3//! Each answers an operator question the plain Rust type cannot express: a
4//! limit that can be lifted, a listener that can be turned off, or a
5//! structured value that `conf` hands over as raw TOML text.
6
7use std::{collections::BTreeMap, fmt, net::SocketAddr, path::Path, str::FromStr, time::Duration};
8
9use bytesize::ByteSize;
10use serde::Deserialize;
11
12use crate::config::{ConfigError, TextSource};
13
14/// A duration that may be explicitly turned off with `"off"` or `"none"`.
15///
16/// "No timeout" has to stay expressible: a trusted link on a controlled
17/// network is a legitimate reason to wait indefinitely, and without `"off"` an
18/// operator who wants that is pushed into writing an absurd number instead —
19/// which reads as a mistake and behaves like one if it is ever reached.
20#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
21pub struct OptionalDuration(pub Option<Duration>);
22
23impl fmt::Display for OptionalDuration {
24    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
25        match self.0 {
26            Some(duration) => write!(formatter, "{}", humantime::format_duration(duration)),
27            None => formatter.write_str("off"),
28        }
29    }
30}
31
32pub fn parse_optional_duration(value: &str) -> Result<OptionalDuration, String> {
33    let trimmed = value.trim();
34    if trimmed.eq_ignore_ascii_case("off") || trimmed.eq_ignore_ascii_case("none") {
35        return Ok(OptionalDuration(None));
36    }
37    humantime::parse_duration(trimmed)
38        .map(|duration| OptionalDuration(Some(duration)))
39        .map_err(|error| error.to_string())
40}
41
42/// A byte limit that may be explicitly lifted with `"unlimited"`.
43///
44/// Like [`OptionalDuration`]'s "off": a trusted deployment may reasonably opt
45/// out of enforcement, and spelling that as an absurd number reads as a
46/// mistake. Usage is still accounted and reported either way.
47#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
48pub struct OptionalBytes(pub Option<ByteSize>);
49
50impl fmt::Display for OptionalBytes {
51    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self.0 {
53            Some(bytes) => write!(formatter, "{bytes}"),
54            None => formatter.write_str("unlimited"),
55        }
56    }
57}
58
59pub fn parse_optional_bytes(value: &str) -> Result<OptionalBytes, String> {
60    let trimmed = value.trim();
61    if trimmed.eq_ignore_ascii_case("unlimited") {
62        return Ok(OptionalBytes(None));
63    }
64    trimmed.parse().map(|bytes| OptionalBytes(Some(bytes)))
65}
66
67/// A listener address that may be explicitly disabled with `"off"`.
68///
69/// Mirrors [`OptionalDuration`]: turning one listener off is how an operator
70/// says "this protocol only", and an absurd address is not a way to spell that.
71#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
72pub struct OptionalAddress(pub Option<SocketAddr>);
73
74impl fmt::Display for OptionalAddress {
75    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
76        match self.0 {
77            Some(address) => write!(formatter, "{address}"),
78            None => formatter.write_str("off"),
79        }
80    }
81}
82
83pub fn parse_optional_address(value: &str) -> Result<OptionalAddress, String> {
84    let trimmed = value.trim();
85    if trimmed.eq_ignore_ascii_case("off") {
86        return Ok(OptionalAddress(None));
87    }
88    trimmed
89        .parse()
90        .map(|address| OptionalAddress(Some(address)))
91        .map_err(|error| format!("{error}"))
92}
93
94/// A TOML table of entries keyed by the name an operator chose.
95///
96/// `conf` hands a table-valued parameter over as its own TOML text rather than
97/// as a parsed value, so each of these has to parse itself. Keyed by name so
98/// uniqueness is structural: TOML rejects a duplicate key, where an array of
99/// tables with a `name` field would need a validation rule.
100#[derive(Debug, Deserialize)]
101#[serde(transparent)]
102pub struct TomlTable<T>(pub BTreeMap<String, T>);
103
104// Hand-written rather than derived: an empty table is meaningful for every `T`,
105// and deriving would demand `T: Default` for no reason.
106impl<T> Default for TomlTable<T> {
107    fn default() -> Self {
108        Self(BTreeMap::new())
109    }
110}
111
112impl<T: serde::de::DeserializeOwned> FromStr for TomlTable<T> {
113    type Err = toml::de::Error;
114
115    fn from_str(value: &str) -> Result<Self, Self::Err> {
116        toml::from_str(value).map_err(|mut error| {
117            // Entries can contain credentials beside the invalid field.
118            error.set_input(None);
119            error
120        })
121    }
122}
123
124/// One TOML value handed over as its own text.
125///
126/// `conf` gives a table-valued parameter as raw TOML rather than as a parsed
127/// value, so each of these parses itself. The same shape also lets an
128/// environment override carry a TOML fragment, which keeps a structured value
129/// overridable rather than file-only.
130#[derive(Clone, Debug, Deserialize)]
131#[serde(transparent)]
132pub struct TomlValue<T>(pub T);
133
134impl<T: serde::de::DeserializeOwned> FromStr for TomlValue<T> {
135    type Err = toml::de::Error;
136
137    fn from_str(value: &str) -> Result<Self, Self::Err> {
138        #[derive(Deserialize)]
139        struct Wrapper<T> {
140            value: T,
141        }
142        // Wrapped in a key so a bare inline table parses as a document, which
143        // is the form both a file fragment and an environment value take.
144        toml::from_str::<Wrapper<T>>(&format!("value = {value}")).map(|wrapper| Self(wrapper.value))
145    }
146}
147
148/// Reads a credential that also has a command-line flag.
149///
150/// Arguments are visible to every local user through the process list, so
151/// the flag only ever names a file; it is never the credential itself. It
152/// sits at the CLI's place in the precedence order, above TOML and the
153/// environment.
154pub fn read_credential(
155    label: &str,
156    source: Option<&TextSource>,
157    cli_file: Option<&Path>,
158) -> Result<Option<String>, ConfigError> {
159    match cli_file {
160        Some(path) => TextSource::File(path.to_path_buf()).read(label).map(Some),
161        None => source.map(|source| source.read(label)).transpose(),
162    }
163}