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
779    const SECOND: Duration = Duration::from_secs(1);
780    const MINUTE: Duration = Duration::from_secs(60);
781    const HOUR: Duration = Duration::from_secs(60 * 60);
782    const DAY: Duration = Duration::from_secs(24 * 60 * 60);
783
784    #[test]
785    fn parses_the_same_as_go() {
786        // Test cases from Go's `time.ParseDuration` test suite.
787        for (input, expected) in [
788            ("0", Duration::ZERO),
789            ("5s", 5 * SECOND),
790            ("30s", 30 * SECOND),
791            ("1478s", 1478 * SECOND),
792            ("100ns", Duration::from_nanos(100)),
793            ("11us", Duration::from_micros(11)),
794            ("11\u{00b5}s", Duration::from_micros(11)),
795            ("11\u{03bc}s", Duration::from_micros(11)),
796            ("1ms", Duration::from_millis(1)),
797            // Go takes a point with digits on only one side.
798            ("5.s", 5 * SECOND),
799            (".5s", Duration::from_millis(500)),
800            ("1h", HOUR),
801            ("1m", MINUTE),
802            ("3h30m", 3 * HOUR + 30 * MINUTE),
803            (
804                "10.5s4m",
805                4 * MINUTE + 10 * SECOND + Duration::from_millis(500),
806            ),
807            (
808                "1h2m3s4ms5us6ns",
809                HOUR + 2 * MINUTE
810                    + 3 * SECOND
811                    + Duration::from_millis(4)
812                    + Duration::from_micros(5)
813                    + Duration::from_nanos(6),
814            ),
815            (
816                "39h9m14.425s",
817                39 * HOUR + 9 * MINUTE + 14 * SECOND + Duration::from_millis(425),
818            ),
819            ("0.3333333333333333333h", 20 * MINUTE),
820        ] {
821            assert_eq!(
822                input.parse::<ConfigDuration>().unwrap(),
823                ConfigDuration(expected),
824                "parsing {input:?}"
825            );
826        }
827    }
828
829    #[test]
830    fn parses_days() {
831        assert_eq!(
832            "30d".parse::<ConfigDuration>().unwrap(),
833            ConfigDuration::from_days(30)
834        );
835        assert_eq!(
836            "1d12h".parse::<ConfigDuration>().unwrap(),
837            ConfigDuration(DAY + 12 * HOUR)
838        );
839    }
840
841    #[test]
842    fn rejects_bad_input() {
843        for input in [
844            // A sign with nothing behind it, and more signs than Go allows.
845            "",
846            "+",
847            "++1s",
848            "-1s", // A number with no unit, anywhere in the string.
849            "10",
850            "1s0",
851            "1h30", // A unit that does not exist, or a stray separator.
852            "10y",
853            "5sec",
854            "abc",
855            "1 s",
856            "5s ",
857            "1..2s",
858            // Too large for `Duration`, which once panicked here.
859            "99999999999999999999999999s",
860            "184467440737095516160s",
861            "9223372036854775807d",
862            "1000000000000000000000d",
863        ] {
864            assert!(
865                input.parse::<ConfigDuration>().is_err(),
866                "{input:?} should not parse, got {:?}",
867                input.parse::<ConfigDuration>()
868            );
869        }
870    }
871
872    /// A term with a unit but no number says so, rather than reporting an
873    /// unknown unit for a unit that plainly exists.
874    #[test]
875    fn a_unit_with_no_number_says_so() {
876        for (input, expected) in [
877            ("s", "`s` in duration `s` has no number in front of it"),
878            ("ms", "`ms` in duration `ms` has no number in front of it"),
879            ("forever", "unknown unit `forever`"),
880            // The unit scan runs to the next digit, so a space belongs to the
881            // unit and the whole token is what is unknown.
882            ("1h ms", "unknown unit `h ms`"),
883        ] {
884            let message = input.parse::<ConfigDuration>().unwrap_err().to_string();
885            assert!(
886                message.contains(expected),
887                "parsing {input:?} reported {message:?}"
888            );
889        }
890    }
891
892    /// Every rejection names the value it rejected, so that a configuration
893    /// error tells the reader what to correct.
894    #[test]
895    fn rejection_messages_quote_the_input() {
896        for (input, expected) in [
897            ("-1s", "duration `-1s` cannot be negative"),
898            ("10", "`10` in duration `10` carries no unit"),
899            ("5sec", "unknown unit `sec` in duration `5sec`"),
900            // The space lands inside the unit, and the message shows it.
901            ("1 s", "unknown unit ` s` in duration `1 s`"),
902            ("99999999999999999999999999s", "is too large"),
903            ("", "empty duration"),
904        ] {
905            let message = input.parse::<ConfigDuration>().unwrap_err().to_string();
906            assert!(
907                message.contains(expected),
908                "parsing {input:?} reported {message:?}, which omits {expected:?}"
909            );
910        }
911    }
912
913    /// The edge of the representable range: `u64::MAX` seconds and a
914    /// fraction of a second below the next one parse and print back exactly,
915    /// and one nanosecond more is rejected rather than wrapped.
916    #[test]
917    fn accepts_the_largest_representable_duration() {
918        let max = format!("{}s999999999ns", u64::MAX);
919        let parsed: ConfigDuration = max.parse().unwrap();
920        assert_eq!(parsed, ConfigDuration::from(Duration::MAX));
921        assert_eq!(
922            parsed.to_string().parse::<ConfigDuration>().unwrap(),
923            parsed
924        );
925        let over = format!("{}s1000000000ns", u64::MAX);
926        assert!(matches!(
927            over.parse::<ConfigDuration>(),
928            Err(ParseError::Overflow { .. })
929        ));
930    }
931
932    /// A superseded spelling accepts a whole number however JSON spells it,
933    /// and says what is wrong with anything else.
934    ///
935    /// This workspace enables `serde_json`'s `arbitrary_precision`, which hands
936    /// a non-integer literal to `deserialize_any` as a map rather than an
937    /// `f64`. Without a `visit_map` the reader is told "invalid type: map",
938    /// naming nothing they wrote, so each spelling below is pinned. YAML still
939    /// delivers a real `f64`, and is covered too.
940    #[test]
941    fn a_superseded_spelling_reads_any_whole_number() {
942        #[derive(Debug, serde::Deserialize)]
943        struct Config {
944            #[serde(default, alias = "nap_secs", deserialize_with = "duration_nap")]
945            nap: Option<ConfigDuration>,
946        }
947        crate::duration_setting!(duration_nap, "nap", LegacyUnit::Secs);
948
949        for json in [
950            r#"{"nap_secs": 10}"#,
951            r#"{"nap_secs": 10.0}"#,
952            r#"{"nap_secs": 1e1}"#,
953        ] {
954            let config: Config = serde_json::from_str(json).unwrap();
955            assert_eq!(
956                config.nap,
957                Some(ConfigDuration::from_secs(10)),
958                "parsing {json}"
959            );
960        }
961        // `u64::MAX` is the largest bare number; 2^64 and above are refused, even
962        // though `u64::MAX as f64` rounds to exactly 2^64.
963        let config: Config = serde_json::from_str(r#"{"nap_secs": 18446744073709551615}"#).unwrap();
964        assert!(config.nap.is_some());
965        for json in [
966            r#"{"nap_secs": 18446744073709551616}"#,
967            r#"{"nap_secs": 18446744073709551617}"#,
968            r#"{"nap_secs": 1.8446744073709552e19}"#,
969        ] {
970            let error = serde_json::from_str::<Config>(json)
971                .unwrap_err()
972                .to_string();
973            assert!(
974                error.contains("is neither"),
975                "parsing {json} reported {error}"
976            );
977        }
978
979        let yaml: Config = serde_yaml::from_str("nap_secs: 10.0").unwrap();
980        assert_eq!(yaml.nap, Some(ConfigDuration::from_secs(10)));
981
982        for (bad, quoted) in [
983            (r#"{"nap_secs": 10.5}"#, "`10.5`"),
984            (r#"{"nap_secs": -5}"#, "cannot be negative"),
985            (r#"{"nap_secs": {}}"#, "`{}`"),
986            // Quoted as written, not as an `f64` would print it.
987            (r#"{"nap_secs": 10.50}"#, "`10.50`"),
988            (r#"{"nap_secs": {"secs": 1}}"#, "`an object`"),
989        ] {
990            let error = serde_json::from_str::<Config>(bad).unwrap_err().to_string();
991            assert!(error.contains(quoted), "parsing {bad} reported {error}");
992            assert!(
993                !error.contains("invalid type: map"),
994                "parsing {bad} reported {error}"
995            );
996        }
997        let error = serde_yaml::from_str::<Config>("nap_secs: 10.5")
998            .unwrap_err()
999            .to_string();
1000        assert!(error.contains("`10.5`"), "{error}");
1001    }
1002
1003    /// More days than a `u64` of seconds holds saturate rather than wrapping
1004    /// in release builds or panicking in debug ones.
1005    #[test]
1006    fn from_days_saturates() {
1007        assert_eq!(
1008            ConfigDuration::from_days(2),
1009            ConfigDuration::from_secs(2 * 86_400)
1010        );
1011        assert_eq!(
1012            ConfigDuration::from_days(u64::MAX),
1013            ConfigDuration::from_secs(u64::MAX)
1014        );
1015    }
1016
1017    /// The "no limit" value an older release wrote out on its own is read
1018    /// without a deprecation warning, which would otherwise quote a duration of
1019    /// hundreds of millions of years the reader never wrote. Any other bare
1020    /// number still warns.
1021    #[test]
1022    fn the_no_limit_value_is_read_without_a_warning() {
1023        use std::sync::atomic::{AtomicBool, Ordering};
1024        let warned = AtomicBool::new(false);
1025        let max = duration_from_legacy_number::<serde_json::Error>(
1026            &warned,
1027            "max_output_buffer_time",
1028            LegacyUnit::Millis,
1029            u64::MAX,
1030        )
1031        .unwrap();
1032        assert_eq!(max, ConfigDuration::from_millis(u64::MAX));
1033        assert!(!warned.load(Ordering::Relaxed));
1034
1035        duration_from_legacy_number::<serde_json::Error>(
1036            &warned,
1037            "max_output_buffer_time",
1038            LegacyUnit::Millis,
1039            500,
1040        )
1041        .unwrap();
1042        assert!(warned.load(Ordering::Relaxed));
1043    }
1044
1045    /// A fraction scales as an exact ratio, not as a floating-point product.
1046    /// `f64` carries about sixteen significant digits, so the value below lands
1047    /// a nanosecond low when it goes through one; the parser must not.
1048    #[test]
1049    fn fractions_scale_exactly() {
1050        const DAY_NANOS: u128 = 24 * 60 * 60 * 1_000_000_000;
1051        let digits = "718656392856533598";
1052        let exact = (DAY_NANOS * digits.parse::<u128>().unwrap()
1053            + 10u128.pow(digits.len() as u32) / 2)
1054            / 10u128.pow(digits.len() as u32);
1055        assert_eq!(exact, 62_091_912_342_805);
1056
1057        let parsed: ConfigDuration = format!("0.{digits}d").parse().unwrap();
1058        assert_eq!(Duration::from(parsed).as_nanos(), exact);
1059
1060        // Halves go away from zero, and a whole part adds on top of the ratio.
1061        assert_eq!(
1062            "0.5s".parse::<ConfigDuration>().unwrap(),
1063            ConfigDuration::from_millis(500)
1064        );
1065        assert_eq!(
1066            "1.5s".parse::<ConfigDuration>().unwrap(),
1067            ConfigDuration::from_millis(1500)
1068        );
1069        assert_eq!(
1070            "0.0000000005s".parse::<ConfigDuration>().unwrap(),
1071            ConfigDuration::from_nanos(1)
1072        );
1073    }
1074
1075    /// Both spellings of a setting reach one field, so a configuration that
1076    /// writes both is rejected rather than silently keeping one. The message
1077    /// names the current spelling, which is the field serde knows.
1078    #[test]
1079    fn writing_both_spellings_is_rejected() {
1080        #[derive(Debug, serde::Deserialize)]
1081        struct Config {
1082            #[serde(
1083                default,
1084                alias = "nap_secs",
1085                deserialize_with = "duration_nap",
1086                skip_serializing_if = "Option::is_none"
1087            )]
1088            nap: Option<ConfigDuration>,
1089        }
1090        crate::duration_setting!(duration_nap, "nap", LegacyUnit::Secs);
1091
1092        assert_eq!(
1093            serde_json::from_str::<Config>(r#"{"nap": "30s"}"#)
1094                .unwrap()
1095                .nap,
1096            Some(ConfigDuration::from_secs(30))
1097        );
1098        assert_eq!(
1099            serde_json::from_str::<Config>(r#"{"nap_secs": 30}"#)
1100                .unwrap()
1101                .nap,
1102            Some(ConfigDuration::from_secs(30))
1103        );
1104        let error = serde_json::from_str::<Config>(r#"{"nap": "30s", "nap_secs": 30}"#)
1105            .unwrap_err()
1106            .to_string();
1107        assert!(error.contains("duplicate field `nap`"), "{error}");
1108    }
1109
1110    /// A duration of more than 2^53 seconds survives being written out and read
1111    /// back. Scaling such a value through `f64` used to land four minutes away,
1112    /// which the pipeline manager saw as a stored configuration changing value
1113    /// on its own. The two spellings below differ only in how the parser must
1114    /// reach the same number of seconds.
1115    #[test]
1116    fn large_values_round_trip_exactly() {
1117        let written = "128644735584426d23h5m38s";
1118        let parsed: ConfigDuration = written.parse().unwrap();
1119        assert_eq!(parsed.to_string(), written);
1120        assert_eq!(
1121            parsed.as_secs(),
1122            128_644_735_584_426 * 24 * 60 * 60 + 23 * 60 * 60 + 5 * 60 + 38
1123        );
1124        assert_eq!(
1125            "11114905154494489538s".parse::<ConfigDuration>().unwrap(),
1126            parsed
1127        );
1128    }
1129
1130    #[test]
1131    fn displays_in_decomposed_units() {
1132        for (duration, expected) in [
1133            (ConfigDuration::ZERO, "0s"),
1134            (ConfigDuration::from_days(30), "30d"),
1135            (ConfigDuration::from_secs(3600), "1h"),
1136            (ConfigDuration::from_secs(100), "1m40s"),
1137            (ConfigDuration::from_millis(500), "500ms"),
1138            (ConfigDuration::from_micros(1_000_000), "1s"),
1139            (ConfigDuration::from_nanos(1), "1ns"),
1140            (ConfigDuration(HOUR + 30 * MINUTE + 10 * SECOND), "1h30m10s"),
1141        ] {
1142            assert_eq!(duration.to_string(), expected);
1143        }
1144    }
1145
1146    #[test]
1147    fn round_trips_through_json() {
1148        for text in [
1149            "0s", "30d", "1h", "1m30s", "500ms", "1ns", "1h30m10s", "1d12h",
1150        ] {
1151            let json = format!("\"{text}\"");
1152            let duration: ConfigDuration = serde_json::from_str(&json).unwrap();
1153            assert_eq!(serde_json::to_string(&duration).unwrap(), json);
1154        }
1155    }
1156
1157    /// Property-based tests.
1158    ///
1159    /// The tests above enumerate cases by hand and therefore cover only the
1160    /// inputs somebody thought of. These explore the input space instead, with
1161    /// generators weighted towards the edges of the representable range, where
1162    /// the parser's floating-point arithmetic once panicked.
1163    mod properties {
1164        use super::*;
1165        use proptest::prelude::*;
1166
1167        /// Every unit the parser accepts, with its length in nanoseconds.
1168        const UNITS: [(&str, u64); 7] = [
1169            ("ns", 1),
1170            ("us", 1_000),
1171            ("ms", 1_000_000),
1172            ("s", 1_000_000_000),
1173            ("m", 60 * 1_000_000_000),
1174            ("h", 60 * 60 * 1_000_000_000),
1175            ("d", 24 * 60 * 60 * 1_000_000_000),
1176        ];
1177
1178        /// Durations spanning the whole representable range, as
1179        /// `(seconds, subsecond nanoseconds)`.
1180        ///
1181        /// [`nanos`] reaches only `u64::MAX` nanoseconds, about 213503 days,
1182        /// and a whole region above it went untested: the pipeline manager
1183        /// stores durations of billions of days, and those are exactly the ones
1184        /// the parser's arithmetic used to round. The strategy names the top of
1185        /// the range explicitly, because a uniform `u64` rarely lands there.
1186        fn seconds_and_nanos() -> impl Strategy<Value = (u64, u32)> {
1187            let seconds = prop_oneof![
1188                1 => Just(0u64),
1189                1 => Just(u64::MAX),
1190                1 => Just(11_114_905_154_334_422_338u64),
1191                2 => 0u64..1_000,
1192                2 => (1u64 << 53)..u64::MAX,
1193                5 => any::<u64>(),
1194            ];
1195            (
1196                seconds,
1197                prop_oneof![1 => Just(0u32), 3 => 0u32..1_000_000_000],
1198            )
1199        }
1200
1201        /// Nanosecond counts spanning the range `ConfigDuration::from_nanos` covers.
1202        ///
1203        /// A uniform `u64` almost never lands on zero, on one nanosecond, on
1204        /// the largest value, or below a second, which is where the formatter
1205        /// and the parser are likeliest to disagree, so the strategy names
1206        /// those regions explicitly.
1207        fn nanos() -> impl Strategy<Value = u64> {
1208            const DAY_NS: u64 = 24 * 60 * 60 * 1_000_000_000;
1209            prop_oneof![
1210                1 => Just(0u64),
1211                1 => Just(1u64),
1212                1 => Just(u64::MAX),
1213                1 => Just(DAY_NS),
1214                2 => 0u64..1_000,
1215                2 => 0u64..1_000_000_000,
1216                2 => 0u64..DAY_NS,
1217                6 => any::<u64>(),
1218            ]
1219        }
1220
1221        /// Text drawn from the parser's own alphabet, plus arbitrary unicode.
1222        ///
1223        /// A uniformly random string is rejected at its first character and
1224        /// exercises nothing; these reach the number parser, the unit table and
1225        /// the overflow checks. The long digit runs matter most: a magnitude
1226        /// far past `Duration` used to panic inside the standard
1227        /// library rather than return an error.
1228        fn duration_like_text() -> impl Strategy<Value = String> {
1229            prop_oneof![
1230                2 => any::<String>(),
1231                3 => "[-+0-9. nsumhd\u{00b5}\u{03bc}]{0,40}",
1232                3 => "[0-9]{1,40}(ns|us|\u{00b5}s|\u{03bc}s|ms|s|m|h|d)",
1233                2 => "[0-9]{1,25}\\.[0-9]{1,25}(ns|ms|s|h|d)",
1234                2 => "[+-]?[0-9]{0,8}[a-z]{0,4}([0-9]{0,8}[a-z]{0,4}){0,3}",
1235            ]
1236        }
1237
1238        /// Terms of a multi-term duration, as `(number, unit index)` pairs.
1239        ///
1240        /// The magnitudes stay small so that every sum is representable, which
1241        /// keeps the summation property free of discarded cases.
1242        fn terms() -> impl Strategy<Value = Vec<(u32, usize)>> {
1243            prop::collection::vec((0u32..1_000, 0usize..UNITS.len()), 1..6)
1244        }
1245
1246        proptest! {
1247            #![proptest_config(ProptestConfig::with_cases(256))]
1248
1249            /// Formatting a duration and parsing the result returns the same
1250            /// value. This is the central promise of the type: a configuration
1251            /// written back out reloads unchanged.
1252            #[test]
1253            fn display_round_trips(nanos in nanos()) {
1254                let duration = ConfigDuration::from_nanos(nanos);
1255                let text = duration.to_string();
1256                prop_assert_eq!(
1257                    text.parse::<ConfigDuration>().map_err(|e| e.to_string()),
1258                    Ok(duration),
1259                    "formatted as {:?}",
1260                    text
1261                );
1262            }
1263
1264            /// Formatting and parsing back returns the same value across the
1265            /// whole representable range, not just the part `from_nanos`
1266            /// reaches. Durations above 2^53 seconds are where the parser's
1267            /// arithmetic has to stay exact.
1268            #[test]
1269            fn display_round_trips_across_the_whole_range(
1270                (seconds, nanos) in seconds_and_nanos()
1271            ) {
1272                let duration = ConfigDuration::from(Duration::new(seconds, nanos));
1273                let text = duration.to_string();
1274                prop_assert_eq!(
1275                    text.parse::<ConfigDuration>().map_err(|e| e.to_string()),
1276                    Ok(duration),
1277                    "formatted as {:?}",
1278                    text
1279                );
1280            }
1281
1282            /// JSON is the format configurations travel in, and serde must
1283            /// agree with `FromStr`: the JSON string is the `Display` form, and
1284            /// parsing that text directly yields the same value.
1285            #[test]
1286            fn serde_agrees_with_from_str(nanos in nanos()) {
1287                let duration = ConfigDuration::from_nanos(nanos);
1288                let json = serde_json::to_string(&duration).unwrap();
1289                prop_assert_eq!(&json, &format!("\"{duration}\""));
1290                prop_assert_eq!(serde_json::from_str::<ConfigDuration>(&json).unwrap(), duration);
1291                prop_assert_eq!(
1292                    json.trim_matches('"').parse::<ConfigDuration>().unwrap(),
1293                    duration
1294                );
1295            }
1296
1297            /// Parsing answers `Ok` or `Err` for any input and never panics.
1298            /// Overflowing values reach `Duration`, whose arithmetic
1299            /// panics on overflow, so the parser must keep them inside its own
1300            /// checked forms.
1301            #[test]
1302            fn parsing_never_panics(text in duration_like_text()) {
1303                let parsed = text.parse::<ConfigDuration>();
1304                // Whatever the outcome, the error message names the input, so
1305                // that a rejected configuration value tells the reader which
1306                // one to correct.
1307                if let Err(error) = parsed {
1308                    prop_assert!(!error.to_string().is_empty());
1309                }
1310            }
1311
1312            /// A value written as several terms equals the sum of its terms
1313            /// parsed on their own, which is what chaining `1h30m` means.
1314            #[test]
1315            fn terms_sum(terms in terms()) {
1316                let mut written = String::new();
1317                let mut sum = ConfigDuration::ZERO;
1318                for (value, unit) in &terms {
1319                    let (unit, _) = UNITS[*unit];
1320                    let term = format!("{value}{unit}");
1321                    let term_duration: Duration = term.parse::<ConfigDuration>().unwrap().into();
1322                    sum = ConfigDuration::from(Duration::from(sum) + term_duration);
1323                    written.push_str(&term);
1324                }
1325                prop_assert_eq!(written.parse::<ConfigDuration>().unwrap(), sum);
1326            }
1327
1328            /// The same quantity written in different units parses to the same
1329            /// value, so no unit's conversion factor has drifted.
1330            #[test]
1331            fn units_are_equivalent(count in 0u64..1_000_000) {
1332                let same = |smaller: String, larger: String| -> Result<(), TestCaseError> {
1333                    prop_assert_eq!(
1334                        smaller.parse::<ConfigDuration>().unwrap(),
1335                        larger.parse::<ConfigDuration>().unwrap(),
1336                        "{} and {} differ",
1337                        smaller,
1338                        larger
1339                    );
1340                    Ok(())
1341                };
1342                same(format!("{}ns", count * 1_000), format!("{count}us"))?;
1343                same(format!("{}us", count * 1_000), format!("{count}ms"))?;
1344                same(format!("{}ms", count * 1_000), format!("{count}s"))?;
1345                same(format!("{}s", count * 60), format!("{count}m"))?;
1346                same(format!("{}m", count * 60), format!("{count}h"))?;
1347                same(format!("{}h", count * 24), format!("{count}d"))?;
1348                // All three spellings of the microsecond unit agree.
1349                same(format!("{count}us"), format!("{count}\u{00b5}s"))?;
1350                same(format!("{count}us"), format!("{count}\u{03bc}s"))?;
1351            }
1352
1353            /// Ordering follows the underlying nanosecond counts, so that
1354            /// comparisons of parsed configuration values mean what they read.
1355            #[test]
1356            fn ordering_follows_nanoseconds(left in nanos(), right in nanos()) {
1357                let parse = |nanos: u64| {
1358                    ConfigDuration::from_nanos(nanos)
1359                        .to_string()
1360                        .parse::<ConfigDuration>()
1361                        .unwrap()
1362                };
1363                prop_assert_eq!(parse(left).cmp(&parse(right)), left.cmp(&right));
1364            }
1365
1366            /// A leading `+` is accepted and changes nothing, while a leading
1367            /// `-` is always rejected: configuration durations cannot run
1368            /// backwards.
1369            #[test]
1370            fn signs_behave(nanos in nanos()) {
1371                let text = ConfigDuration::from_nanos(nanos).to_string();
1372                prop_assert_eq!(
1373                    format!("+{text}").parse::<ConfigDuration>().unwrap(),
1374                    text.parse::<ConfigDuration>().unwrap()
1375                );
1376                prop_assert_eq!(
1377                    format!("-{text}").parse::<ConfigDuration>().unwrap_err(),
1378                    ParseError::Negative { input: format!("-{text}") }
1379                );
1380            }
1381
1382            /// A fractional term rounds to the nearest nanosecond, halves up,
1383            /// rather than truncating as Go's parser does. Four digits after
1384            /// the point of a microsecond reach below one nanosecond, so the
1385            /// rounding is exercised.
1386            #[test]
1387            fn fractional_terms_round(micros in 0u64..1_000_000, fraction in 0u64..10_000) {
1388                let text = format!("{micros}.{fraction:04}us");
1389                let expected = ConfigDuration::from_nanos(micros * 1_000 + (fraction + 5) / 10);
1390                prop_assert_eq!(text.parse::<ConfigDuration>().unwrap(), expected);
1391            }
1392        }
1393    }
1394}