Skip to main content

feldera_types/
duration.rs

1//! A human-readable duration type for the pipeline configuration.
2//!
3//! Every duration-shaped field in the pipeline configuration uses [`ConfigDuration`],
4//! so that one format covers seconds, milliseconds, microseconds, and days
5//! instead of a different unit baked into each field name.
6//!
7//! The syntax is the one Go's [`time.ParseDuration`] documents, which many
8//! tools accept and users already know. Feldera extends it with a `d` (day)
9//! unit, because configuration values such as checkpoint retention are
10//! naturally expressed in days, and narrows it by rejecting a negative
11//! duration, which no configuration setting accepts.
12//!
13//! [`time.ParseDuration`]: https://pkg.go.dev/time#ParseDuration
14
15use std::{cmp::Ordering, fmt, str::FromStr, time::Duration};
16
17use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
18
19/// A duration written as a number and a unit, such as `500ms`, `30s`, `1h30m`
20/// or `30d`.
21///
22/// Accepted units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, `h`, and `d`. A
23/// value may chain several terms, as in `1h30m`, and the terms are summed. A
24/// bare `0` is also accepted.
25#[derive(Copy, Clone, PartialEq, Eq, Hash, Default)]
26pub struct ConfigDuration(Duration);
27
28/// The unit list quoted in error messages, built from [`UNITS`] at compile
29/// time so that the two cannot drift apart. The Greek mu spelling is left out:
30/// it is accepted, but the micro sign already stands for it.
31const EXPECTED_UNITS: &str = match str::from_utf8(&EXPECTED_UNITS_BYTES) {
32    Ok(text) => text,
33    Err(_) => panic!("unit names are UTF-8"),
34};
35
36const EXPECTED_UNITS_BYTES: [u8; EXPECTED_UNITS_LEN] = {
37    let mut buf = [0u8; EXPECTED_UNITS_LEN];
38    render_expected_units(&mut buf);
39    buf
40};
41
42const EXPECTED_UNITS_LEN: usize = render_expected_units(&mut []);
43
44/// Writes the unit list into `buf`, or only measures it when `buf` is empty,
45/// and returns its length in bytes.
46const fn render_expected_units(buf: &mut [u8]) -> usize {
47    let mut i = 0;
48    while i < UNITS.len() {
49        i += 1;
50    }
51
52    let mut at = put(buf, 0, "expected one of ");
53    let mut i = 0;
54    while i < UNITS.len() {
55        let (name, _) = UNITS[i];
56        i += 1;
57        if i > 1 {
58            at = put(buf, at, ", ");
59        }
60        at = put(buf, at, "'");
61        at = put(buf, at, name);
62        at = put(buf, at, "'");
63    }
64    at
65}
66
67/// Appends `text` to `buf` at `at`, or only measures it when `buf` is empty,
68/// and returns the position after it.
69const fn put(buf: &mut [u8], at: usize, text: &str) -> usize {
70    let bytes = text.as_bytes();
71    if !buf.is_empty() {
72        let mut i = 0;
73        while i < bytes.len() {
74            buf[at + i] = bytes[i];
75            i += 1;
76        }
77    }
78    at + bytes.len()
79}
80
81/// Errors returned when parsing a [`ConfigDuration`] from a string.
82///
83/// Every variant quotes the text it rejected, so that a configuration error
84/// tells the reader which value to correct.
85#[derive(Debug, thiserror::Error, Eq, PartialEq)]
86#[non_exhaustive]
87pub enum ParseError {
88    /// The string holds no number at all.
89    #[error("empty duration: write `0`, or a number and a unit such as `500ms`")]
90    Empty,
91
92    /// The string carries a unit that does not exist.
93    #[error("unknown unit `{unit}` in duration `{input}`: {EXPECTED_UNITS}")]
94    InvalidUnit { unit: String, input: String },
95
96    /// A term carries a unit but no number in front of it, as in `s`.
97    #[error("`{unit}` in duration `{input}` has no number in front of it")]
98    MissingNumber { unit: String, input: String },
99
100    /// The string carries a number with no unit after it.
101    #[error("`{number}` in duration `{input}` carries no unit: {EXPECTED_UNITS}")]
102    NoUnit { number: String, input: String },
103
104    /// The string carries a leading `-`. Configuration durations cannot be
105    /// negative, unlike Go's and Kubernetes' durations.
106    #[error("duration `{input}` cannot be negative")]
107    Negative { input: String },
108
109    /// The value does not fit in a [`Duration`].
110    #[error("duration `{input}` is too large: at most {} days", u64::MAX / (24 * 60 * 60))]
111    Overflow { input: String },
112}
113
114const NANOS_PER_SECOND: u128 = 1_000_000_000;
115
116impl ConfigDuration {
117    pub const ZERO: ConfigDuration = ConfigDuration(Duration::ZERO);
118
119    pub const fn from_nanos(nanos: u64) -> Self {
120        Self(Duration::from_nanos(nanos))
121    }
122
123    pub const fn from_micros(micros: u64) -> Self {
124        Self(Duration::from_micros(micros))
125    }
126
127    pub const fn from_millis(millis: u64) -> Self {
128        Self(Duration::from_millis(millis))
129    }
130
131    pub const fn from_secs(secs: u64) -> Self {
132        Self(Duration::from_secs(secs))
133    }
134
135    /// A duration of `days` days, or the longest one there is when that many
136    /// days do not fit in a `u64` of seconds.
137    pub const fn from_days(days: u64) -> Self {
138        Self(Duration::from_secs(days.saturating_mul(24 * 60 * 60)))
139    }
140
141    pub const fn as_micros(self) -> u128 {
142        self.0.as_micros()
143    }
144
145    pub const fn as_millis(self) -> u128 {
146        self.0.as_millis()
147    }
148
149    pub const fn as_secs(self) -> u64 {
150        self.0.as_secs()
151    }
152
153    pub fn as_secs_f64(self) -> f64 {
154        self.0.as_secs_f64()
155    }
156
157    pub const fn is_zero(self) -> bool {
158        self.0.is_zero()
159    }
160}
161
162impl From<Duration> for ConfigDuration {
163    fn from(duration: Duration) -> Self {
164        Self(duration)
165    }
166}
167
168impl From<ConfigDuration> for Duration {
169    fn from(ConfigDuration(duration): ConfigDuration) -> Self {
170        duration
171    }
172}
173
174impl PartialEq<Duration> for ConfigDuration {
175    fn eq(&self, other: &Duration) -> bool {
176        self.0 == *other
177    }
178}
179
180impl PartialOrd for ConfigDuration {
181    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
182        Some(self.cmp(other))
183    }
184}
185
186impl Ord for ConfigDuration {
187    fn cmp(&self, other: &Self) -> Ordering {
188        self.0.cmp(&other.0)
189    }
190}
191
192impl PartialOrd<Duration> for ConfigDuration {
193    fn partial_cmp(&self, other: &Duration) -> Option<Ordering> {
194        self.0.partial_cmp(other)
195    }
196}
197
198/// Every accepted unit, with its length in nanoseconds.
199///
200/// Longest first, so that a scan matching the table in order cannot take `m`
201/// from the front of `ms`.
202const UNITS: [(&str, u128); 9] = [
203    ("ns", 1),
204    ("us", 1_000),
205    // U+00B5 is the "micro sign", U+03BC is "Greek small letter mu". Both are
206    // written for microseconds in the wild, so both are accepted.
207    ("\u{00b5}s", 1_000),
208    ("\u{03bc}s", 1_000),
209    ("ms", 1_000_000),
210    ("s", NANOS_PER_SECOND),
211    ("m", 60 * NANOS_PER_SECOND),
212    ("h", 60 * 60 * NANOS_PER_SECOND),
213    ("d", 24 * 60 * 60 * NANOS_PER_SECOND),
214];
215
216/// How many digits after the point are read.
217///
218/// A fraction scales as an exact ratio, so the digits and the power of ten
219/// below them both have to fit in a `u128` alongside the unit. Eighteen digits
220/// leave room to spare, and the first digit dropped is worth less than a
221/// millionth of a nanosecond even for a term counted in days.
222const MAX_FRACTION_DIGITS: usize = 18;
223
224/// Reads a run of decimal digits, or `None` if they do not fit in a `u128`.
225fn digits_to_u128(digits: &str) -> Option<u128> {
226    digits.bytes().try_fold(0u128, |acc, byte| {
227        acc.checked_mul(10)?.checked_add(u128::from(byte - b'0'))
228    })
229}
230
231impl FromStr for ConfigDuration {
232    type Err = ParseError;
233
234    /// Reads the format described on [`ConfigDuration`]: a run of terms, each a
235    /// number and a unit, summed together.
236    ///
237    /// The scan walks the string once. Each term contributes
238    /// `whole * unit + round(fraction * unit)`, accumulated in nanoseconds as a
239    /// `u128`, so no step goes through floating point and a value near the top
240    /// of the representable range keeps every digit.
241    fn from_str(s: &str) -> Result<Self, Self::Err> {
242        let input = s;
243        let overflow = || ParseError::Overflow {
244            input: input.to_string(),
245        };
246
247        if input.starts_with('-') {
248            return Err(ParseError::Negative {
249                input: input.to_string(),
250            });
251        }
252        // At most one sign, so a run of them is not a number.
253        let body = input.strip_prefix('+').unwrap_or(input);
254        if body.is_empty() {
255            return Err(ParseError::Empty);
256        }
257        // A lone zero is the one value that carries no unit.
258        if body == "0" {
259            return Ok(ConfigDuration::ZERO);
260        }
261
262        let bytes = body.as_bytes();
263        let mut at = 0;
264        let mut total: u128 = 0;
265
266        while at < bytes.len() {
267            let number_at = at;
268
269            // A number: digits, then at most one point and more digits.
270            let whole_at = at;
271            while at < bytes.len() && bytes[at].is_ascii_digit() {
272                at += 1;
273            }
274            let whole = &body[whole_at..at];
275
276            let mut fraction = "";
277            let has_point = at < bytes.len() && bytes[at] == b'.';
278            if has_point {
279                at += 1;
280                let fraction_at = at;
281                while at < bytes.len() && bytes[at].is_ascii_digit() {
282                    at += 1;
283                }
284                fraction = &body[fraction_at..at];
285            }
286            let number = &body[number_at..at];
287
288            // The unit runs to whatever starts the next number. This always
289            // advances: a byte that stops the unit scan starts a number.
290            let unit_at = at;
291            while at < bytes.len() && !bytes[at].is_ascii_digit() && bytes[at] != b'.' {
292                at += 1;
293            }
294            let unit = &body[unit_at..at];
295
296            if whole.is_empty() && fraction.is_empty() {
297                // Nothing numeric here at all. Which half is wrong depends on
298                // whether the rest is a unit: `s` is one and wants a number in
299                // front of it, `forever` is not one at all.
300                let known = UNITS.iter().any(|(name, _)| *name == unit);
301                return Err(if known {
302                    ParseError::MissingNumber {
303                        unit: unit.to_string(),
304                        input: input.to_string(),
305                    }
306                } else {
307                    ParseError::InvalidUnit {
308                        unit: unit.to_string(),
309                        input: input.to_string(),
310                    }
311                });
312            }
313            // A point with no digits behind it, as in `5.s`, is a whole number,
314            // as it is in Go. `1..2s` still fails below: the second point
315            // starts a number where a unit belongs.
316            if unit.is_empty() {
317                return Err(ParseError::NoUnit {
318                    number: number.to_string(),
319                    input: input.to_string(),
320                });
321            }
322            let Some(&(_, unit_nanos)) = UNITS.iter().find(|(name, _)| *name == unit) else {
323                return Err(ParseError::InvalidUnit {
324                    unit: unit.to_string(),
325                    input: input.to_string(),
326                });
327            };
328
329            let mut term = digits_to_u128(whole)
330                .ok_or_else(overflow)?
331                .checked_mul(unit_nanos)
332                .ok_or_else(overflow)?;
333
334            if !fraction.is_empty() {
335                // An exact ratio rather than a floating-point product: `0.5s`
336                // is `unit_nanos * 5 / 10`. The quotient is rounded to the
337                // nearest nanosecond, halves away from zero.
338                let kept = fraction.len().min(MAX_FRACTION_DIGITS);
339                let numerator = digits_to_u128(&fraction[..kept]).ok_or_else(overflow)?;
340                let denominator = 10u128.pow(kept as u32);
341                let scaled = unit_nanos.checked_mul(numerator).ok_or_else(overflow)?;
342                let rounded = (scaled + denominator / 2) / denominator;
343                term = term.checked_add(rounded).ok_or_else(overflow)?;
344            }
345
346            total = total.checked_add(term).ok_or_else(overflow)?;
347        }
348
349        let seconds = u64::try_from(total / NANOS_PER_SECOND).map_err(|_| overflow())?;
350        Ok(ConfigDuration(Duration::new(
351            seconds,
352            (total % NANOS_PER_SECOND) as u32,
353        )))
354    }
355}
356
357impl fmt::Display for ConfigDuration {
358    /// Writes the `ConfigDuration` as a sequence of unit terms, largest first,
359    /// e.g. `ConfigDuration::from_secs(100)` writes `1m40s`.
360    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361        let mut remain = self.0.as_nanos();
362        if remain == 0 {
363            return f.write_str("0s");
364        }
365
366        // Largest unit first. The ASCII names are the ones written out; the
367        // micro sign and the Greek mu are read but never written.
368        for &(unit, base) in UNITS.iter().rev().filter(|(name, _)| name.is_ascii()) {
369            let unit_mult = remain / base;
370            if unit_mult != 0 {
371                remain %= base;
372                write!(f, "{unit_mult}{unit}")?;
373            }
374        }
375        Ok(())
376    }
377}
378
379impl fmt::Debug for ConfigDuration {
380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381        fmt::Display::fmt(self, f)
382    }
383}
384
385impl Serialize for ConfigDuration {
386    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
387        serializer.collect_str(self)
388    }
389}
390
391impl<'de> Deserialize<'de> for ConfigDuration {
392    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
393        struct Visitor;
394
395        impl de::Visitor<'_> for Visitor {
396            type Value = ConfigDuration;
397
398            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
399                f.write_str("a duration such as \"500ms\", \"30s\", \"1h30m\" or \"30d\"")
400            }
401
402            fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
403                value.parse::<ConfigDuration>().map_err(de::Error::custom)
404            }
405        }
406
407        deserializer.deserialize_str(Visitor)
408    }
409}
410
411// No `ToSchema` implementation. Each field of this type carries
412// `#[schema(value_type = Option<String>)]` instead, which renders the field as
413// an inline OpenAPI string and keeps the field's own description. A schema for
414// this type would make every such field a reference to one shared schema, and
415// `utoipa` drops a field's description once it becomes a reference. Each field's
416// doc comment carries an example, and the accepted format is documented once
417// in the user documentation.
418
419/// The unit in which a setting's superseded numeric spelling was written.
420///
421/// Each duration setting once took a bare number, and the unit lived in the
422/// field name (`clock_resolution_usecs`) or only in the documentation
423/// (`retention_min_age`, which counted days). Those numbers still parse, so the
424/// unit has to survive somewhere; it lives here.
425#[derive(Clone, Copy, Debug, Eq, PartialEq)]
426pub enum LegacyUnit {
427    Micros,
428    Millis,
429    Secs,
430    Days,
431}
432
433impl LegacyUnit {
434    /// The length one unit stands for, in nanoseconds.
435    pub const fn nanos(self) -> u64 {
436        match self {
437            LegacyUnit::Micros => 1_000,
438            LegacyUnit::Millis => 1_000_000,
439            LegacyUnit::Secs => 1_000_000_000,
440            LegacyUnit::Days => 24 * 60 * 60 * 1_000_000_000,
441        }
442    }
443}
444
445/// A [`ConfigDuration`] of `nanos` nanoseconds, or the longest one there is.
446///
447/// Saturating rather than failing, because every caller converts a value an
448/// older release already accepted. `max_output_buffer_time_millis` defaulted to
449/// `usize::MAX`, and that default was written into every output connector
450/// configuration, so rejecting it would stop those pipelines from loading at
451/// all.
452fn duration_from_nanos_saturating(nanos: u128) -> ConfigDuration {
453    const NANOS_PER_SECOND_U128: u128 = NANOS_PER_SECOND;
454    match u64::try_from(nanos / NANOS_PER_SECOND_U128) {
455        Ok(seconds) => ConfigDuration(Duration::new(
456            seconds,
457            (nanos % NANOS_PER_SECOND_U128) as u32,
458        )),
459        Err(_) => ConfigDuration(Duration::MAX),
460    }
461}
462
463/// Warns, once per setting per process, that a value arrived as a bare number,
464/// and returns the duration that number stands for.
465///
466/// The warning quotes the equivalent in the current format, so that the reader
467/// can correct the configuration by copying the text out of the log.
468///
469/// Warning once rather than on every value is deliberate: this runs inside a
470/// `deserialize_with` function, and the pipeline manager re-parses every
471/// pipeline's stored configuration on each automaton poll, so warning per parse
472/// would fill the log at the polling rate.
473pub fn duration_from_legacy_number<E: de::Error>(
474    warned: &std::sync::atomic::AtomicBool,
475    field: &str,
476    unit: LegacyUnit,
477    value: u64,
478) -> Result<ConfigDuration, E> {
479    let duration = duration_from_nanos_saturating(u128::from(value) * u128::from(unit.nanos()));
480    // `u64::MAX` is the "no limit" an older release wrote out on its own, as
481    // `max_output_buffer_time_millis` in every output connector's stored and
482    // checkpointed configuration. Warning about it would tell the reader to
483    // write a duration they never wrote.
484    if value != u64::MAX && !warned.swap(true, std::sync::atomic::Ordering::Relaxed) {
485        log::warn!(
486            "configuration field `{field}` was given the bare number {value}, which is \
487             deprecated and is removed no earlier than release 0.368.0; write \
488             `\"{duration}\"` instead"
489        );
490    }
491    Ok(duration)
492}
493
494/// The whole number a JSON or YAML number stands for, or `None` if it is not a
495/// non-negative whole number that fits in a `u64`. JSON and YAML have one
496/// number type, so a whole number may arrive as a float; a fraction of the
497/// legacy unit never had a meaning.
498fn whole_number(value: f64) -> Option<u64> {
499    // `u64::MAX as f64` rounds up to 2^64, so compare against 2^64 itself with
500    // `<`: `<=` would let 2^64 through and saturate it to `u64::MAX`.
501    const TWO_TO_THE_64: f64 = 18_446_744_073_709_551_616.0;
502    (value.is_finite() && value >= 0.0 && value.fract() == 0.0 && value < TWO_TO_THE_64)
503        .then_some(value as u64)
504}
505
506/// Deserializes a duration setting that also accepts the bare number its
507/// earlier spelling took.
508///
509/// A string is parsed as a [`ConfigDuration`]; a number is read in `unit`. Both
510/// spellings therefore reach one field, and the configuration written back out
511/// always carries the current one.
512pub fn duration_or_legacy_number<'de, D>(
513    deserializer: D,
514    warned: &std::sync::atomic::AtomicBool,
515    field: &'static str,
516    unit: LegacyUnit,
517) -> Result<Option<ConfigDuration>, D::Error>
518where
519    D: Deserializer<'de>,
520{
521    struct Visitor<'a> {
522        warned: &'a std::sync::atomic::AtomicBool,
523        field: &'static str,
524        unit: LegacyUnit,
525    }
526
527    impl Visitor<'_> {
528        /// Says what was wrong and quotes it, so the reader can find the value.
529        fn not_a_number<E: de::Error>(field: &str, value: &str) -> E {
530            de::Error::custom(format!(
531                "`{field}` expects a duration such as \"30s\", or a whole number of the unit \
532                 its earlier spelling took; `{value}` is neither"
533            ))
534        }
535    }
536
537    impl<'de> de::Visitor<'de> for Visitor<'_> {
538        type Value = Option<ConfigDuration>;
539
540        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541            f.write_str("a duration such as \"500ms\", \"30s\" or \"1h30m\"")
542        }
543
544        fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
545            value
546                .parse::<ConfigDuration>()
547                .map(Some)
548                .map_err(de::Error::custom)
549        }
550
551        fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> {
552            duration_from_legacy_number(self.warned, self.field, self.unit, value).map(Some)
553        }
554
555        fn visit_i64<E: de::Error>(self, value: i64) -> Result<Self::Value, E> {
556            let value = u64::try_from(value)
557                .map_err(|_| de::Error::custom(format!("`{}` cannot be negative", self.field)))?;
558            self.visit_u64(value)
559        }
560
561        fn visit_f64<E: de::Error>(self, value: f64) -> Result<Self::Value, E> {
562            match whole_number(value) {
563                Some(whole) => self.visit_u64(whole),
564                None => Err(Self::not_a_number(self.field, &value.to_string())),
565            }
566        }
567
568        /// A number that is not an integer, when it comes from `serde_json`.
569        ///
570        /// This workspace turns on `serde_json`'s `arbitrary_precision`, which
571        /// makes such a number reach `deserialize_any` as a one-entry map
572        /// holding the literal text rather than as an `f64`. Without this the
573        /// value never reaches [`Self::visit_f64`] and the reader is told
574        /// "invalid type: map", which names nothing they wrote.
575        fn visit_map<A: de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
576            const NUMBER: &str = "$serde_json::private::Number";
577
578            let Some(key) = map.next_key::<String>()? else {
579                return Err(Self::not_a_number(self.field, "{}"));
580            };
581            if key != NUMBER {
582                return Err(Self::not_a_number(self.field, "an object"));
583            }
584            // Quote the literal as written: `10.50` reformatted as an `f64`
585            // would read `10.5`, which is not what the reader wrote.
586            let text = map.next_value::<String>()?;
587            match text.parse::<f64>().ok().and_then(whole_number) {
588                Some(whole) => self.visit_u64(whole),
589                None => Err(Self::not_a_number(self.field, &text)),
590            }
591        }
592
593        /// An explicit `null`. The nullable settings keep it distinct from an
594        /// absent key; the rest never reach this, because a `null` on them is
595        /// the same as leaving the key out.
596        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
597            Ok(None)
598        }
599    }
600
601    deserializer.deserialize_any(Visitor {
602        warned,
603        field,
604        unit,
605    })
606}
607
608/// Deserializes a duration setting whose earlier spelling was a
609/// [`Duration`], which serde writes as a `{secs, nanos}` object.
610///
611/// NATS's `max_expires` was the only setting shaped this way.
612pub fn duration_or_legacy_struct<'de, D>(
613    deserializer: D,
614    warned: &std::sync::atomic::AtomicBool,
615    field: &'static str,
616) -> Result<Option<ConfigDuration>, D::Error>
617where
618    D: Deserializer<'de>,
619{
620    struct Visitor<'a> {
621        warned: &'a std::sync::atomic::AtomicBool,
622        field: &'static str,
623    }
624
625    impl<'de> de::Visitor<'de> for Visitor<'_> {
626        type Value = Option<ConfigDuration>;
627
628        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629            // Serde builds its "invalid type" messages around this, and they
630            // are what a reader sees for a value of the wrong shape. A bare
631            // number is not listed, because this setting never had one.
632            f.write_str("a duration such as \"30s\", or a {secs, nanos} object")
633        }
634
635        fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
636            value
637                .parse::<ConfigDuration>()
638                .map(Some)
639                .map_err(de::Error::custom)
640        }
641
642        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
643            Ok(None)
644        }
645
646        /// The superseded spelling, a serde-written [`Duration`].
647        ///
648        /// `serde_json`'s `arbitrary_precision`, which this workspace enables,
649        /// also delivers a non-integer number as a map, so the two are told
650        /// apart by their key.
651        fn visit_map<A: de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
652            const NUMBER: &str = "$serde_json::private::Number";
653
654            let (mut secs, mut nanos) = (0u64, 0u32);
655            let mut saw_field = false;
656            while let Some(key) = map.next_key::<String>()? {
657                match key.as_str() {
658                    "secs" => {
659                        secs = map.next_value()?;
660                        saw_field = true;
661                    }
662                    "nanos" => {
663                        nanos = map.next_value()?;
664                        saw_field = true;
665                    }
666                    NUMBER => {
667                        let text = map.next_value::<String>()?;
668                        return Err(de::Error::invalid_type(
669                            de::Unexpected::Other(&format!("the number {text}")),
670                            &self,
671                        ));
672                    }
673                    other => {
674                        return Err(de::Error::unknown_field(other, &["secs", "nanos"]));
675                    }
676                }
677            }
678            if !saw_field {
679                return Err(de::Error::invalid_type(de::Unexpected::Map, &self));
680            }
681
682            let duration = duration_from_nanos_saturating(
683                u128::from(secs) * NANOS_PER_SECOND + u128::from(nanos),
684            );
685            if !self.warned.swap(true, std::sync::atomic::Ordering::Relaxed) {
686                log::warn!(
687                    "configuration field `{}` was given a `{{secs, nanos}}` object, which is \
688                     deprecated and is removed no earlier than release 0.368.0; write \
689                     `\"{duration}\"` instead",
690                    self.field
691                );
692            }
693            Ok(Some(duration))
694        }
695    }
696
697    // Written out rather than derived through `#[serde(untagged)]`: an untagged
698    // enum reports every failure as "data did not match any variant of untagged
699    // enum Either", which leaks an internal name and quotes nothing the reader
700    // wrote. Serde's own "invalid type" messages, built from `expecting` above,
701    // name the value instead.
702    deserializer.deserialize_any(Visitor { warned, field })
703}
704
705/// Like [`duration_setting!`], for the setting whose earlier spelling was a
706/// `{secs, nanos}` object rather than a bare number.
707#[doc(hidden)]
708#[macro_export]
709macro_rules! duration_struct_setting {
710    ($name:ident, $field:literal) => {
711        fn $name<'de, D>(
712            deserializer: D,
713        ) -> ::std::result::Result<Option<$crate::duration::ConfigDuration>, D::Error>
714        where
715            D: ::serde::Deserializer<'de>,
716        {
717            static WARNED: ::std::sync::atomic::AtomicBool =
718                ::std::sync::atomic::AtomicBool::new(false);
719            $crate::duration::duration_or_legacy_struct(deserializer, &WARNED, $field)
720        }
721    };
722}
723
724/// Defines a `deserialize_with` function for a duration setting.
725///
726/// The setting accepts the current spelling, a duration string, and the bare
727/// number its earlier spelling took, read in `unit`. Pair it with
728/// `#[serde(default, alias = "<old key>", deserialize_with = "<name>")]`.
729///
730/// ```ignore
731/// duration_setting!(clock_resolution, "clock_resolution", LegacyUnit::Micros);
732/// ```
733#[doc(hidden)]
734#[macro_export]
735macro_rules! duration_setting {
736    ($name:ident, $field:literal, $unit:expr) => {
737        fn $name<'de, D>(
738            deserializer: D,
739        ) -> ::std::result::Result<Option<$crate::duration::ConfigDuration>, D::Error>
740        where
741            D: ::serde::Deserializer<'de>,
742        {
743            static WARNED: ::std::sync::atomic::AtomicBool =
744                ::std::sync::atomic::AtomicBool::new(false);
745            $crate::duration::duration_or_legacy_number(deserializer, &WARNED, $field, $unit)
746        }
747    };
748}
749
750/// Like [`duration_setting!`], for a setting whose explicit `null` carries
751/// meaning of its own, such as "never do this".
752///
753/// serde maps both a missing key and an explicit `null` to `None`, and these
754/// settings need them apart. The generated function yields
755/// `Option<Option<ConfigDuration>>`: `None` when the key is absent, `Some(None)` for
756/// an explicit `null`, `Some(Some(value))` otherwise.
757#[doc(hidden)]
758#[macro_export]
759macro_rules! nullable_duration_setting {
760    ($name:ident, $field:literal, $unit:expr) => {
761        fn $name<'de, D>(
762            deserializer: D,
763        ) -> ::std::result::Result<Option<Option<$crate::duration::ConfigDuration>>, D::Error>
764        where
765            D: ::serde::Deserializer<'de>,
766        {
767            static WARNED: ::std::sync::atomic::AtomicBool =
768                ::std::sync::atomic::AtomicBool::new(false);
769            $crate::duration::duration_or_legacy_number(deserializer, &WARNED, $field, $unit)
770                .map(Some)
771        }
772    };
773}
774
775#[cfg(test)]
776mod tests {
777    use super::*;
778    use serde::de::value::F64Deserializer;
779
780    const SECOND: Duration = Duration::from_secs(1);
781    const MINUTE: Duration = Duration::from_secs(60);
782    const HOUR: Duration = Duration::from_secs(60 * 60);
783    const DAY: Duration = Duration::from_secs(24 * 60 * 60);
784
785    #[test]
786    fn parses_the_same_as_go() {
787        // Test cases from Go's `time.ParseDuration` test suite.
788        for (input, expected) in [
789            ("0", Duration::ZERO),
790            ("5s", 5 * SECOND),
791            ("30s", 30 * SECOND),
792            ("1478s", 1478 * SECOND),
793            ("100ns", Duration::from_nanos(100)),
794            ("11us", Duration::from_micros(11)),
795            ("11\u{00b5}s", Duration::from_micros(11)),
796            ("11\u{03bc}s", Duration::from_micros(11)),
797            ("1ms", Duration::from_millis(1)),
798            // Go takes a point with digits on only one side.
799            ("5.s", 5 * SECOND),
800            (".5s", Duration::from_millis(500)),
801            ("1h", HOUR),
802            ("1m", MINUTE),
803            ("3h30m", 3 * HOUR + 30 * MINUTE),
804            (
805                "10.5s4m",
806                4 * MINUTE + 10 * SECOND + Duration::from_millis(500),
807            ),
808            (
809                "1h2m3s4ms5us6ns",
810                HOUR + 2 * MINUTE
811                    + 3 * SECOND
812                    + Duration::from_millis(4)
813                    + Duration::from_micros(5)
814                    + Duration::from_nanos(6),
815            ),
816            (
817                "39h9m14.425s",
818                39 * HOUR + 9 * MINUTE + 14 * SECOND + Duration::from_millis(425),
819            ),
820            ("0.3333333333333333333h", 20 * MINUTE),
821        ] {
822            assert_eq!(
823                input.parse::<ConfigDuration>().unwrap(),
824                ConfigDuration(expected),
825                "parsing {input:?}"
826            );
827        }
828    }
829
830    #[test]
831    fn parses_days() {
832        assert_eq!(
833            "30d".parse::<ConfigDuration>().unwrap(),
834            ConfigDuration::from_days(30)
835        );
836        assert_eq!(
837            "1d12h".parse::<ConfigDuration>().unwrap(),
838            ConfigDuration(DAY + 12 * HOUR)
839        );
840    }
841
842    #[test]
843    fn rejects_bad_input() {
844        for input in [
845            // A sign with nothing behind it, and more signs than Go allows.
846            "",
847            "+",
848            "++1s",
849            "-1s", // A number with no unit, anywhere in the string.
850            "10",
851            "1s0",
852            "1h30", // A unit that does not exist, or a stray separator.
853            "10y",
854            "5sec",
855            "abc",
856            "1 s",
857            "5s ",
858            "1..2s",
859            // Too large for `Duration`, which once panicked here.
860            "99999999999999999999999999s",
861            "184467440737095516160s",
862            "9223372036854775807d",
863            "1000000000000000000000d",
864        ] {
865            assert!(
866                input.parse::<ConfigDuration>().is_err(),
867                "{input:?} should not parse, got {:?}",
868                input.parse::<ConfigDuration>()
869            );
870        }
871    }
872
873    /// A term with a unit but no number says so, rather than reporting an
874    /// unknown unit for a unit that plainly exists.
875    #[test]
876    fn a_unit_with_no_number_says_so() {
877        for (input, expected) in [
878            ("s", "`s` in duration `s` has no number in front of it"),
879            ("ms", "`ms` in duration `ms` has no number in front of it"),
880            ("forever", "unknown unit `forever`"),
881            // The unit scan runs to the next digit, so a space belongs to the
882            // unit and the whole token is what is unknown.
883            ("1h ms", "unknown unit `h ms`"),
884        ] {
885            let message = input.parse::<ConfigDuration>().unwrap_err().to_string();
886            assert!(
887                message.contains(expected),
888                "parsing {input:?} reported {message:?}"
889            );
890        }
891    }
892
893    /// Every rejection names the value it rejected, so that a configuration
894    /// error tells the reader what to correct.
895    #[test]
896    fn rejection_messages_quote_the_input() {
897        for (input, expected) in [
898            ("-1s", "duration `-1s` cannot be negative"),
899            ("10", "`10` in duration `10` carries no unit"),
900            ("5sec", "unknown unit `sec` in duration `5sec`"),
901            // The space lands inside the unit, and the message shows it.
902            ("1 s", "unknown unit ` s` in duration `1 s`"),
903            ("99999999999999999999999999s", "is too large"),
904            ("", "empty duration"),
905        ] {
906            let message = input.parse::<ConfigDuration>().unwrap_err().to_string();
907            assert!(
908                message.contains(expected),
909                "parsing {input:?} reported {message:?}, which omits {expected:?}"
910            );
911        }
912    }
913
914    /// The edge of the representable range: `u64::MAX` seconds and a
915    /// fraction of a second below the next one parse and print back exactly,
916    /// and one nanosecond more is rejected rather than wrapped.
917    #[test]
918    fn accepts_the_largest_representable_duration() {
919        let max = format!("{}s999999999ns", u64::MAX);
920        let parsed: ConfigDuration = max.parse().unwrap();
921        assert_eq!(parsed, ConfigDuration::from(Duration::MAX));
922        assert_eq!(
923            parsed.to_string().parse::<ConfigDuration>().unwrap(),
924            parsed
925        );
926        let over = format!("{}s1000000000ns", u64::MAX);
927        assert!(matches!(
928            over.parse::<ConfigDuration>(),
929            Err(ParseError::Overflow { .. })
930        ));
931    }
932
933    /// A superseded spelling accepts a whole number however JSON spells it,
934    /// and says what is wrong with anything else.
935    ///
936    /// This workspace enables `serde_json`'s `arbitrary_precision`, which hands
937    /// a non-integer literal to `deserialize_any` as a map rather than an
938    /// `f64`. Without a `visit_map` the reader is told "invalid type: map",
939    /// naming nothing they wrote, so each spelling below is pinned. A format
940    /// that delivers a real `f64` is covered through `F64Deserializer`.
941    #[test]
942    fn a_superseded_spelling_reads_any_whole_number() {
943        #[derive(Debug, serde::Deserialize)]
944        struct Config {
945            #[serde(default, alias = "nap_secs", deserialize_with = "duration_nap")]
946            nap: Option<ConfigDuration>,
947        }
948        crate::duration_setting!(duration_nap, "nap", LegacyUnit::Secs);
949
950        for json in [
951            r#"{"nap_secs": 10}"#,
952            r#"{"nap_secs": 10.0}"#,
953            r#"{"nap_secs": 1e1}"#,
954        ] {
955            let config: Config = serde_json::from_str(json).unwrap();
956            assert_eq!(
957                config.nap,
958                Some(ConfigDuration::from_secs(10)),
959                "parsing {json}"
960            );
961        }
962        // `u64::MAX` is the largest bare number; 2^64 and above are refused, even
963        // though `u64::MAX as f64` rounds to exactly 2^64.
964        let config: Config = serde_json::from_str(r#"{"nap_secs": 18446744073709551615}"#).unwrap();
965        assert!(config.nap.is_some());
966        for json in [
967            r#"{"nap_secs": 18446744073709551616}"#,
968            r#"{"nap_secs": 18446744073709551617}"#,
969            r#"{"nap_secs": 1.8446744073709552e19}"#,
970        ] {
971            let error = serde_json::from_str::<Config>(json)
972                .unwrap_err()
973                .to_string();
974            assert!(
975                error.contains("is neither"),
976                "parsing {json} reported {error}"
977            );
978        }
979
980        let whole = duration_nap(F64Deserializer::<de::value::Error>::new(10.0)).unwrap();
981        assert_eq!(whole, Some(ConfigDuration::from_secs(10)));
982
983        for (bad, quoted) in [
984            (r#"{"nap_secs": 10.5}"#, "`10.5`"),
985            (r#"{"nap_secs": -5}"#, "cannot be negative"),
986            (r#"{"nap_secs": {}}"#, "`{}`"),
987            // Quoted as written, not as an `f64` would print it.
988            (r#"{"nap_secs": 10.50}"#, "`10.50`"),
989            (r#"{"nap_secs": {"secs": 1}}"#, "`an object`"),
990        ] {
991            let error = serde_json::from_str::<Config>(bad).unwrap_err().to_string();
992            assert!(error.contains(quoted), "parsing {bad} reported {error}");
993            assert!(
994                !error.contains("invalid type: map"),
995                "parsing {bad} reported {error}"
996            );
997        }
998        let error = duration_nap(F64Deserializer::<de::value::Error>::new(10.5))
999            .unwrap_err()
1000            .to_string();
1001        assert!(error.contains("`10.5`"), "{error}");
1002    }
1003
1004    /// More days than a `u64` of seconds holds saturate rather than wrapping
1005    /// in release builds or panicking in debug ones.
1006    #[test]
1007    fn from_days_saturates() {
1008        assert_eq!(
1009            ConfigDuration::from_days(2),
1010            ConfigDuration::from_secs(2 * 86_400)
1011        );
1012        assert_eq!(
1013            ConfigDuration::from_days(u64::MAX),
1014            ConfigDuration::from_secs(u64::MAX)
1015        );
1016    }
1017
1018    /// The "no limit" value an older release wrote out on its own is read
1019    /// without a deprecation warning, which would otherwise quote a duration of
1020    /// hundreds of millions of years the reader never wrote. Any other bare
1021    /// number still warns.
1022    #[test]
1023    fn the_no_limit_value_is_read_without_a_warning() {
1024        use std::sync::atomic::{AtomicBool, Ordering};
1025        let warned = AtomicBool::new(false);
1026        let max = duration_from_legacy_number::<serde_json::Error>(
1027            &warned,
1028            "max_output_buffer_time",
1029            LegacyUnit::Millis,
1030            u64::MAX,
1031        )
1032        .unwrap();
1033        assert_eq!(max, ConfigDuration::from_millis(u64::MAX));
1034        assert!(!warned.load(Ordering::Relaxed));
1035
1036        duration_from_legacy_number::<serde_json::Error>(
1037            &warned,
1038            "max_output_buffer_time",
1039            LegacyUnit::Millis,
1040            500,
1041        )
1042        .unwrap();
1043        assert!(warned.load(Ordering::Relaxed));
1044    }
1045
1046    /// A fraction scales as an exact ratio, not as a floating-point product.
1047    /// `f64` carries about sixteen significant digits, so the value below lands
1048    /// a nanosecond low when it goes through one; the parser must not.
1049    #[test]
1050    fn fractions_scale_exactly() {
1051        const DAY_NANOS: u128 = 24 * 60 * 60 * 1_000_000_000;
1052        let digits = "718656392856533598";
1053        let exact = (DAY_NANOS * digits.parse::<u128>().unwrap()
1054            + 10u128.pow(digits.len() as u32) / 2)
1055            / 10u128.pow(digits.len() as u32);
1056        assert_eq!(exact, 62_091_912_342_805);
1057
1058        let parsed: ConfigDuration = format!("0.{digits}d").parse().unwrap();
1059        assert_eq!(Duration::from(parsed).as_nanos(), exact);
1060
1061        // Halves go away from zero, and a whole part adds on top of the ratio.
1062        assert_eq!(
1063            "0.5s".parse::<ConfigDuration>().unwrap(),
1064            ConfigDuration::from_millis(500)
1065        );
1066        assert_eq!(
1067            "1.5s".parse::<ConfigDuration>().unwrap(),
1068            ConfigDuration::from_millis(1500)
1069        );
1070        assert_eq!(
1071            "0.0000000005s".parse::<ConfigDuration>().unwrap(),
1072            ConfigDuration::from_nanos(1)
1073        );
1074    }
1075
1076    /// Both spellings of a setting reach one field, so a configuration that
1077    /// writes both is rejected rather than silently keeping one. The message
1078    /// names the current spelling, which is the field serde knows.
1079    #[test]
1080    fn writing_both_spellings_is_rejected() {
1081        #[derive(Debug, serde::Deserialize)]
1082        struct Config {
1083            #[serde(
1084                default,
1085                alias = "nap_secs",
1086                deserialize_with = "duration_nap",
1087                skip_serializing_if = "Option::is_none"
1088            )]
1089            nap: Option<ConfigDuration>,
1090        }
1091        crate::duration_setting!(duration_nap, "nap", LegacyUnit::Secs);
1092
1093        assert_eq!(
1094            serde_json::from_str::<Config>(r#"{"nap": "30s"}"#)
1095                .unwrap()
1096                .nap,
1097            Some(ConfigDuration::from_secs(30))
1098        );
1099        assert_eq!(
1100            serde_json::from_str::<Config>(r#"{"nap_secs": 30}"#)
1101                .unwrap()
1102                .nap,
1103            Some(ConfigDuration::from_secs(30))
1104        );
1105        let error = serde_json::from_str::<Config>(r#"{"nap": "30s", "nap_secs": 30}"#)
1106            .unwrap_err()
1107            .to_string();
1108        assert!(error.contains("duplicate field `nap`"), "{error}");
1109    }
1110
1111    /// A duration of more than 2^53 seconds survives being written out and read
1112    /// back. Scaling such a value through `f64` used to land four minutes away,
1113    /// which the pipeline manager saw as a stored configuration changing value
1114    /// on its own. The two spellings below differ only in how the parser must
1115    /// reach the same number of seconds.
1116    #[test]
1117    fn large_values_round_trip_exactly() {
1118        let written = "128644735584426d23h5m38s";
1119        let parsed: ConfigDuration = written.parse().unwrap();
1120        assert_eq!(parsed.to_string(), written);
1121        assert_eq!(
1122            parsed.as_secs(),
1123            128_644_735_584_426 * 24 * 60 * 60 + 23 * 60 * 60 + 5 * 60 + 38
1124        );
1125        assert_eq!(
1126            "11114905154494489538s".parse::<ConfigDuration>().unwrap(),
1127            parsed
1128        );
1129    }
1130
1131    #[test]
1132    fn displays_in_decomposed_units() {
1133        for (duration, expected) in [
1134            (ConfigDuration::ZERO, "0s"),
1135            (ConfigDuration::from_days(30), "30d"),
1136            (ConfigDuration::from_secs(3600), "1h"),
1137            (ConfigDuration::from_secs(100), "1m40s"),
1138            (ConfigDuration::from_millis(500), "500ms"),
1139            (ConfigDuration::from_micros(1_000_000), "1s"),
1140            (ConfigDuration::from_nanos(1), "1ns"),
1141            (ConfigDuration(HOUR + 30 * MINUTE + 10 * SECOND), "1h30m10s"),
1142        ] {
1143            assert_eq!(duration.to_string(), expected);
1144        }
1145    }
1146
1147    #[test]
1148    fn round_trips_through_json() {
1149        for text in [
1150            "0s", "30d", "1h", "1m30s", "500ms", "1ns", "1h30m10s", "1d12h",
1151        ] {
1152            let json = format!("\"{text}\"");
1153            let duration: ConfigDuration = serde_json::from_str(&json).unwrap();
1154            assert_eq!(serde_json::to_string(&duration).unwrap(), json);
1155        }
1156    }
1157
1158    /// Property-based tests.
1159    ///
1160    /// The tests above enumerate cases by hand and therefore cover only the
1161    /// inputs somebody thought of. These explore the input space instead, with
1162    /// generators weighted towards the edges of the representable range, where
1163    /// the parser's floating-point arithmetic once panicked.
1164    mod properties {
1165        use super::*;
1166        use proptest::prelude::*;
1167
1168        /// Every unit the parser accepts, with its length in nanoseconds.
1169        const UNITS: [(&str, u64); 7] = [
1170            ("ns", 1),
1171            ("us", 1_000),
1172            ("ms", 1_000_000),
1173            ("s", 1_000_000_000),
1174            ("m", 60 * 1_000_000_000),
1175            ("h", 60 * 60 * 1_000_000_000),
1176            ("d", 24 * 60 * 60 * 1_000_000_000),
1177        ];
1178
1179        /// Durations spanning the whole representable range, as
1180        /// `(seconds, subsecond nanoseconds)`.
1181        ///
1182        /// [`nanos`] reaches only `u64::MAX` nanoseconds, about 213503 days,
1183        /// and a whole region above it went untested: the pipeline manager
1184        /// stores durations of billions of days, and those are exactly the ones
1185        /// the parser's arithmetic used to round. The strategy names the top of
1186        /// the range explicitly, because a uniform `u64` rarely lands there.
1187        fn seconds_and_nanos() -> impl Strategy<Value = (u64, u32)> {
1188            let seconds = prop_oneof![
1189                1 => Just(0u64),
1190                1 => Just(u64::MAX),
1191                1 => Just(11_114_905_154_334_422_338u64),
1192                2 => 0u64..1_000,
1193                2 => (1u64 << 53)..u64::MAX,
1194                5 => any::<u64>(),
1195            ];
1196            (
1197                seconds,
1198                prop_oneof![1 => Just(0u32), 3 => 0u32..1_000_000_000],
1199            )
1200        }
1201
1202        /// Nanosecond counts spanning the range `ConfigDuration::from_nanos` covers.
1203        ///
1204        /// A uniform `u64` almost never lands on zero, on one nanosecond, on
1205        /// the largest value, or below a second, which is where the formatter
1206        /// and the parser are likeliest to disagree, so the strategy names
1207        /// those regions explicitly.
1208        fn nanos() -> impl Strategy<Value = u64> {
1209            const DAY_NS: u64 = 24 * 60 * 60 * 1_000_000_000;
1210            prop_oneof![
1211                1 => Just(0u64),
1212                1 => Just(1u64),
1213                1 => Just(u64::MAX),
1214                1 => Just(DAY_NS),
1215                2 => 0u64..1_000,
1216                2 => 0u64..1_000_000_000,
1217                2 => 0u64..DAY_NS,
1218                6 => any::<u64>(),
1219            ]
1220        }
1221
1222        /// Text drawn from the parser's own alphabet, plus arbitrary unicode.
1223        ///
1224        /// A uniformly random string is rejected at its first character and
1225        /// exercises nothing; these reach the number parser, the unit table and
1226        /// the overflow checks. The long digit runs matter most: a magnitude
1227        /// far past `Duration` used to panic inside the standard
1228        /// library rather than return an error.
1229        fn duration_like_text() -> impl Strategy<Value = String> {
1230            prop_oneof![
1231                2 => any::<String>(),
1232                3 => "[-+0-9. nsumhd\u{00b5}\u{03bc}]{0,40}",
1233                3 => "[0-9]{1,40}(ns|us|\u{00b5}s|\u{03bc}s|ms|s|m|h|d)",
1234                2 => "[0-9]{1,25}\\.[0-9]{1,25}(ns|ms|s|h|d)",
1235                2 => "[+-]?[0-9]{0,8}[a-z]{0,4}([0-9]{0,8}[a-z]{0,4}){0,3}",
1236            ]
1237        }
1238
1239        /// Terms of a multi-term duration, as `(number, unit index)` pairs.
1240        ///
1241        /// The magnitudes stay small so that every sum is representable, which
1242        /// keeps the summation property free of discarded cases.
1243        fn terms() -> impl Strategy<Value = Vec<(u32, usize)>> {
1244            prop::collection::vec((0u32..1_000, 0usize..UNITS.len()), 1..6)
1245        }
1246
1247        proptest! {
1248            #![proptest_config(ProptestConfig::with_cases(256))]
1249
1250            /// Formatting a duration and parsing the result returns the same
1251            /// value. This is the central promise of the type: a configuration
1252            /// written back out reloads unchanged.
1253            #[test]
1254            fn display_round_trips(nanos in nanos()) {
1255                let duration = ConfigDuration::from_nanos(nanos);
1256                let text = duration.to_string();
1257                prop_assert_eq!(
1258                    text.parse::<ConfigDuration>().map_err(|e| e.to_string()),
1259                    Ok(duration),
1260                    "formatted as {:?}",
1261                    text
1262                );
1263            }
1264
1265            /// Formatting and parsing back returns the same value across the
1266            /// whole representable range, not just the part `from_nanos`
1267            /// reaches. Durations above 2^53 seconds are where the parser's
1268            /// arithmetic has to stay exact.
1269            #[test]
1270            fn display_round_trips_across_the_whole_range(
1271                (seconds, nanos) in seconds_and_nanos()
1272            ) {
1273                let duration = ConfigDuration::from(Duration::new(seconds, nanos));
1274                let text = duration.to_string();
1275                prop_assert_eq!(
1276                    text.parse::<ConfigDuration>().map_err(|e| e.to_string()),
1277                    Ok(duration),
1278                    "formatted as {:?}",
1279                    text
1280                );
1281            }
1282
1283            /// JSON is the format configurations travel in, and serde must
1284            /// agree with `FromStr`: the JSON string is the `Display` form, and
1285            /// parsing that text directly yields the same value.
1286            #[test]
1287            fn serde_agrees_with_from_str(nanos in nanos()) {
1288                let duration = ConfigDuration::from_nanos(nanos);
1289                let json = serde_json::to_string(&duration).unwrap();
1290                prop_assert_eq!(&json, &format!("\"{duration}\""));
1291                prop_assert_eq!(serde_json::from_str::<ConfigDuration>(&json).unwrap(), duration);
1292                prop_assert_eq!(
1293                    json.trim_matches('"').parse::<ConfigDuration>().unwrap(),
1294                    duration
1295                );
1296            }
1297
1298            /// Parsing answers `Ok` or `Err` for any input and never panics.
1299            /// Overflowing values reach `Duration`, whose arithmetic
1300            /// panics on overflow, so the parser must keep them inside its own
1301            /// checked forms.
1302            #[test]
1303            fn parsing_never_panics(text in duration_like_text()) {
1304                let parsed = text.parse::<ConfigDuration>();
1305                // Whatever the outcome, the error message names the input, so
1306                // that a rejected configuration value tells the reader which
1307                // one to correct.
1308                if let Err(error) = parsed {
1309                    prop_assert!(!error.to_string().is_empty());
1310                }
1311            }
1312
1313            /// A value written as several terms equals the sum of its terms
1314            /// parsed on their own, which is what chaining `1h30m` means.
1315            #[test]
1316            fn terms_sum(terms in terms()) {
1317                let mut written = String::new();
1318                let mut sum = ConfigDuration::ZERO;
1319                for (value, unit) in &terms {
1320                    let (unit, _) = UNITS[*unit];
1321                    let term = format!("{value}{unit}");
1322                    let term_duration: Duration = term.parse::<ConfigDuration>().unwrap().into();
1323                    sum = ConfigDuration::from(Duration::from(sum) + term_duration);
1324                    written.push_str(&term);
1325                }
1326                prop_assert_eq!(written.parse::<ConfigDuration>().unwrap(), sum);
1327            }
1328
1329            /// The same quantity written in different units parses to the same
1330            /// value, so no unit's conversion factor has drifted.
1331            #[test]
1332            fn units_are_equivalent(count in 0u64..1_000_000) {
1333                let same = |smaller: String, larger: String| -> Result<(), TestCaseError> {
1334                    prop_assert_eq!(
1335                        smaller.parse::<ConfigDuration>().unwrap(),
1336                        larger.parse::<ConfigDuration>().unwrap(),
1337                        "{} and {} differ",
1338                        smaller,
1339                        larger
1340                    );
1341                    Ok(())
1342                };
1343                same(format!("{}ns", count * 1_000), format!("{count}us"))?;
1344                same(format!("{}us", count * 1_000), format!("{count}ms"))?;
1345                same(format!("{}ms", count * 1_000), format!("{count}s"))?;
1346                same(format!("{}s", count * 60), format!("{count}m"))?;
1347                same(format!("{}m", count * 60), format!("{count}h"))?;
1348                same(format!("{}h", count * 24), format!("{count}d"))?;
1349                // All three spellings of the microsecond unit agree.
1350                same(format!("{count}us"), format!("{count}\u{00b5}s"))?;
1351                same(format!("{count}us"), format!("{count}\u{03bc}s"))?;
1352            }
1353
1354            /// Ordering follows the underlying nanosecond counts, so that
1355            /// comparisons of parsed configuration values mean what they read.
1356            #[test]
1357            fn ordering_follows_nanoseconds(left in nanos(), right in nanos()) {
1358                let parse = |nanos: u64| {
1359                    ConfigDuration::from_nanos(nanos)
1360                        .to_string()
1361                        .parse::<ConfigDuration>()
1362                        .unwrap()
1363                };
1364                prop_assert_eq!(parse(left).cmp(&parse(right)), left.cmp(&right));
1365            }
1366
1367            /// A leading `+` is accepted and changes nothing, while a leading
1368            /// `-` is always rejected: configuration durations cannot run
1369            /// backwards.
1370            #[test]
1371            fn signs_behave(nanos in nanos()) {
1372                let text = ConfigDuration::from_nanos(nanos).to_string();
1373                prop_assert_eq!(
1374                    format!("+{text}").parse::<ConfigDuration>().unwrap(),
1375                    text.parse::<ConfigDuration>().unwrap()
1376                );
1377                prop_assert_eq!(
1378                    format!("-{text}").parse::<ConfigDuration>().unwrap_err(),
1379                    ParseError::Negative { input: format!("-{text}") }
1380                );
1381            }
1382
1383            /// A fractional term rounds to the nearest nanosecond, halves up,
1384            /// rather than truncating as Go's parser does. Four digits after
1385            /// the point of a microsecond reach below one nanosecond, so the
1386            /// rounding is exercised.
1387            #[test]
1388            fn fractional_terms_round(micros in 0u64..1_000_000, fraction in 0u64..10_000) {
1389                let text = format!("{micros}.{fraction:04}us");
1390                let expected = ConfigDuration::from_nanos(micros * 1_000 + (fraction + 5) / 10);
1391                prop_assert_eq!(text.parse::<ConfigDuration>().unwrap(), expected);
1392            }
1393        }
1394    }
1395}