Skip to main content

schedr_config/
units.rs

1//! Durations (`"30s"`, `"5m"`, `"1h30m"`) and sizes (`"4MiB"`) in configuration values.
2
3use std::borrow::Cow;
4use std::fmt;
5use std::fmt::Write as _;
6use std::time::Duration;
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::Serializer;
10use serde::de::{self, Deserializer, Visitor};
11
12#[cfg(test)]
13mod tests;
14
15/// Why a string isn't a valid duration or size.
16#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
17pub enum UnitError {
18    /// Not a duration such as `30s`, `5m` or `1h30m`.
19    #[error("`{0}` is not a duration (use e.g. `500ms`, `30s`, `5m`, `1h30m`, `2d`)")]
20    Duration(String),
21    /// Not a size such as `512B`, `64KiB` or `4MiB`.
22    #[error("`{0}` is not a size (use e.g. `512B`, `64KiB`, `4MiB`, `1GiB`)")]
23    Size(String),
24    /// Not a memory reserve: a percentage up to 90 % or a size.
25    #[error("`{0}` is not a memory reserve (use e.g. `25%`, at most `90%`, or a size like `1GiB`)")]
26    Reserve(String),
27}
28
29/// Parses a duration: one or more `<number><unit>` parts with units `ms`, `s`, `m`, `h`, `d`,
30/// each unit at most once and from largest to smallest (`1h30m`, not `30m1h`).
31///
32/// # Errors
33///
34/// Returns [`UnitError::Duration`] for anything else, including an empty string and a
35/// number without a unit.
36pub fn parse_duration(s: &str) -> Result<Duration, UnitError> {
37    const UNITS: [(&str, u64); 5] = [
38        ("d", 86_400_000),
39        ("h", 3_600_000),
40        ("m", 60_000),
41        ("s", 1_000),
42        ("ms", 1),
43    ];
44    let error = || UnitError::Duration(s.to_owned());
45    let mut rest = s;
46    let mut total_ms: u64 = 0;
47    let mut last_unit = None;
48    while !rest.is_empty() {
49        let digits = rest.find(|c: char| !c.is_ascii_digit()).ok_or_else(error)?;
50        if digits == 0 {
51            return Err(error());
52        }
53        let number: u64 = rest[..digits].parse().map_err(|_| error())?;
54        rest = &rest[digits..];
55        let unit_len = rest
56            .find(|c: char| c.is_ascii_digit())
57            .unwrap_or(rest.len());
58        let unit = &rest[..unit_len];
59        let index = UNITS
60            .iter()
61            .position(|(name, _)| *name == unit)
62            .ok_or_else(error)?;
63        if last_unit.is_some_and(|last| index <= last) {
64            return Err(error());
65        }
66        last_unit = Some(index);
67        let part = number.checked_mul(UNITS[index].1).ok_or_else(error)?;
68        total_ms = total_ms.checked_add(part).ok_or_else(error)?;
69        rest = &rest[unit_len..];
70    }
71    if last_unit.is_none() {
72        return Err(error());
73    }
74    Ok(Duration::from_millis(total_ms))
75}
76
77/// Parses a size: a whole number followed by `B`, `KiB`, `MiB` or `GiB`.
78///
79/// # Errors
80///
81/// Returns [`UnitError::Size`] for anything else (decimal units such as `MB` aren't
82/// accepted, to avoid confusing them with binary ones).
83pub fn parse_size(s: &str) -> Result<u64, UnitError> {
84    const UNITS: [(&str, u64); 4] = [
85        ("B", 1),
86        ("KiB", 1 << 10),
87        ("MiB", 1 << 20),
88        ("GiB", 1 << 30),
89    ];
90    let error = || UnitError::Size(s.to_owned());
91    let digits = s.find(|c: char| !c.is_ascii_digit()).ok_or_else(error)?;
92    if digits == 0 {
93        return Err(error());
94    }
95    let number: u64 = s[..digits].parse().map_err(|_| error())?;
96    let factor = UNITS
97        .iter()
98        .find(|(name, _)| *name == &s[digits..])
99        .map(|(_, f)| *f)
100        .ok_or_else(error)?;
101    number.checked_mul(factor).ok_or_else(error)
102}
103
104/// A serde `deserialize_with` helper for duration fields.
105///
106/// # Errors
107///
108/// Fails for a value that isn't a string, or a string [`parse_duration`] rejects.
109pub fn deserialize_duration<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
110    struct DurationVisitor;
111
112    impl Visitor<'_> for DurationVisitor {
113        type Value = Duration;
114
115        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116            f.write_str("a duration string such as `30s` or `1h30m`")
117        }
118
119        fn visit_str<E: de::Error>(self, s: &str) -> Result<Duration, E> {
120            parse_duration(s).map_err(E::custom)
121        }
122    }
123
124    d.deserialize_str(DurationVisitor)
125}
126
127/// A serde `deserialize_with` helper for a file mode in octal text (`"0640"`). A whole number is
128/// taken by its digits, as the environment gives `SCHEDR_CONFIG__WORKER__LOG_MODE=0640` as
129/// 640: those digits are read as octal too, and checked as the text would be.
130///
131/// # Errors
132///
133/// Fails for a value that is neither a string nor a whole number.
134pub fn deserialize_mode_text<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
135    struct ModeVisitor;
136
137    impl Visitor<'_> for ModeVisitor {
138        type Value = String;
139
140        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141            f.write_str("a file mode in octal such as \"0640\"")
142        }
143
144        fn visit_str<E: de::Error>(self, s: &str) -> Result<String, E> {
145            Ok(s.to_owned())
146        }
147
148        fn visit_u64<E: de::Error>(self, n: u64) -> Result<String, E> {
149            Ok(format!("0{n}"))
150        }
151
152        fn visit_i64<E: de::Error>(self, n: i64) -> Result<String, E> {
153            Ok(format!("0{n}"))
154        }
155    }
156
157    d.deserialize_any(ModeVisitor)
158}
159
160/// A serde `deserialize_with` helper for size fields.
161///
162/// # Errors
163///
164/// Fails for a value that isn't a string, or a string [`parse_size`] rejects.
165pub fn deserialize_size<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
166    struct SizeVisitor;
167
168    impl Visitor<'_> for SizeVisitor {
169        type Value = u64;
170
171        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172            f.write_str("a size string such as `4MiB` or `10GiB`")
173        }
174
175        fn visit_str<E: de::Error>(self, s: &str) -> Result<u64, E> {
176            parse_size(s).map_err(E::custom)
177        }
178    }
179
180    d.deserialize_str(SizeVisitor)
181}
182
183/// A serde `deserialize_with` helper for optional duration fields (`None` when left out).
184///
185/// # Errors
186///
187/// Fails for a value that isn't a string, or a string [`parse_duration`] rejects.
188pub fn deserialize_optional_duration<'de, D: Deserializer<'de>>(
189    d: D,
190) -> Result<Option<Duration>, D::Error> {
191    deserialize_duration(d).map(Some)
192}
193
194/// A serde `deserialize_with` helper for optional size fields (`None` when left out).
195///
196/// # Errors
197///
198/// Fails for a value that isn't a string, or a string [`parse_size`] rejects.
199pub fn deserialize_optional_size<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
200    deserialize_size(d).map(Some)
201}
202
203/// Writes a duration as [`parse_duration`] reads it, in the largest units that are exact
204/// (`2m`, not `120s`; `1h30m`; `0s` for zero).
205#[must_use]
206pub fn format_duration(duration: Duration) -> String {
207    const UNITS: [(&str, u128); 5] = [
208        ("d", 86_400_000),
209        ("h", 3_600_000),
210        ("m", 60_000),
211        ("s", 1_000),
212        ("ms", 1),
213    ];
214    let mut rest = duration.as_millis();
215    if rest == 0 {
216        return "0s".to_owned();
217    }
218    let mut text = String::new();
219    for (name, ms) in UNITS {
220        if rest >= ms {
221            let _ = write!(text, "{}{name}", rest / ms);
222            rest %= ms;
223        }
224    }
225    text
226}
227
228/// Writes a size as [`parse_size`] reads it, in the largest unit that is exact (`4MiB`, not
229/// `4096KiB`).
230#[must_use]
231pub fn format_size(bytes: u64) -> String {
232    const UNITS: [(&str, u64); 3] = [("GiB", 1 << 30), ("MiB", 1 << 20), ("KiB", 1 << 10)];
233    UNITS
234        .iter()
235        .find(|(_, factor)| bytes != 0 && bytes.is_multiple_of(*factor))
236        .map_or_else(
237            || format!("{bytes}B"),
238            |(name, factor)| format!("{}{name}", bytes / factor),
239        )
240}
241
242/// A serde `serialize_with` helper for duration fields (see [`format_duration`]).
243///
244/// # Errors
245///
246/// The serializer's.
247pub fn serialize_duration<S: Serializer>(duration: &Duration, s: S) -> Result<S::Ok, S::Error> {
248    s.serialize_str(&format_duration(*duration))
249}
250
251/// A serde `serialize_with` helper for optional duration fields (see [`format_duration`]).
252///
253/// # Errors
254///
255/// The serializer's.
256pub fn serialize_optional_duration<S: Serializer>(
257    duration: &Option<Duration>,
258    s: S,
259) -> Result<S::Ok, S::Error> {
260    match duration {
261        Some(duration) => s.serialize_some(&format_duration(*duration)),
262        None => s.serialize_none(),
263    }
264}
265
266/// A serde `serialize_with` helper for optional size fields (see [`format_size`]).
267///
268/// # Errors
269///
270/// The serializer's.
271pub fn serialize_optional_size<S: Serializer>(size: &Option<u64>, s: S) -> Result<S::Ok, S::Error> {
272    match size {
273        Some(bytes) => s.serialize_some(&format_size(*bytes)),
274        None => s.serialize_none(),
275    }
276}
277
278/// Writes a size as [`format_size`] does.
279///
280/// # Errors
281///
282/// The serializer's.
283pub fn serialize_size<S: Serializer>(size: &u64, s: S) -> Result<S::Ok, S::Error> {
284    s.serialize_str(&format_size(*size))
285}
286
287/// The JSON Schema of a duration field: a string with format `duration`.
288#[derive(Debug)]
289pub struct DurationText;
290
291impl JsonSchema for DurationText {
292    fn schema_name() -> Cow<'static, str> {
293        "Duration".into()
294    }
295
296    fn json_schema(_: &mut SchemaGenerator) -> Schema {
297        json_schema!({
298            "type": "string",
299            "format": "duration",
300            "description": "A duration such as `500ms`, `30s`, `5m`, `1h30m` or `2d`."
301        })
302    }
303}
304
305/// The JSON Schema of a size field: a string with format `size`.
306#[derive(Debug)]
307pub struct SizeText;
308
309impl JsonSchema for SizeText {
310    fn schema_name() -> Cow<'static, str> {
311        "Size".into()
312    }
313
314    fn json_schema(_: &mut SchemaGenerator) -> Schema {
315        json_schema!({
316            "type": "string",
317            "format": "size",
318            "description": "A size such as `512B`, `64KiB`, `4MiB` or `1GiB`."
319        })
320    }
321}
322
323/// `[worker] memory_reserve`: the part of the pod's memory limit kept out of task budgets.
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub enum MemoryReserve {
326    /// A percentage of the limit (`25%`).
327    Percent(u8),
328    /// A size (`1GiB`).
329    Size(u64),
330}
331
332/// Parses a memory reserve: `<n>%` with `n` at most 90, or a size (see [`parse_size`]).
333///
334/// # Errors
335///
336/// Returns [`UnitError::Reserve`] for anything else.
337pub fn parse_reserve(s: &str) -> Result<MemoryReserve, UnitError> {
338    let error = || UnitError::Reserve(s.to_owned());
339    match s.strip_suffix('%') {
340        Some(number) => match number.parse::<u8>() {
341            Ok(percent) if percent <= 90 => Ok(MemoryReserve::Percent(percent)),
342            _ => Err(error()),
343        },
344        None => parse_size(s).map(MemoryReserve::Size).map_err(|_| error()),
345    }
346}
347
348/// Writes a memory reserve as [`parse_reserve`] reads it.
349#[must_use]
350pub fn format_reserve(reserve: MemoryReserve) -> String {
351    match reserve {
352        MemoryReserve::Percent(percent) => format!("{percent}%"),
353        MemoryReserve::Size(bytes) => format_size(bytes),
354    }
355}
356
357impl<'de> serde::Deserialize<'de> for MemoryReserve {
358    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
359        let text = String::deserialize(d)?;
360        parse_reserve(&text).map_err(de::Error::custom)
361    }
362}
363
364impl serde::Serialize for MemoryReserve {
365    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
366        s.serialize_str(&format_reserve(*self))
367    }
368}
369
370impl JsonSchema for MemoryReserve {
371    fn schema_name() -> Cow<'static, str> {
372        "MemoryReserve".into()
373    }
374
375    fn json_schema(_: &mut SchemaGenerator) -> Schema {
376        json_schema!({
377            "type": "string",
378            "format": "reserve",
379            "description": "A percentage of the pod's memory limit (`25%`, at most `90%`) or a size (`1GiB`)."
380        })
381    }
382}