Skip to main content

dora_message/
config.rs

1use core::fmt;
2use std::{
3    collections::{BTreeMap, BTreeSet},
4    str::FromStr,
5    time::Duration,
6};
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11use crate::descriptor;
12pub use crate::id::{DataId, NodeId, OperatorId};
13
14/// Filter for the `dora/logs` virtual input.
15///
16/// The wire form parsed by [`FromStr`] / rendered by [`Display`](fmt::Display)
17/// is `dora/logs/{level}/{node}`, so a `node_filter` can only be expressed
18/// together with a `min_level`. Parsing therefore never produces a filter with
19/// `node_filter: Some(_)` while `min_level` is `None`. That combination is still
20/// constructible directly (both fields are public); when it is rendered, the
21/// `stdout` level is emitted to keep the node restriction — see the
22/// [`Display`](fmt::Display) impl of [`InputMapping`]. A `Stdout` minimum is the
23/// most permissive level filter ([`LogLevelOrStdout::passes`](crate::common::LogLevelOrStdout::passes)
24/// lets every message through it), so it delivers the same messages as `None`
25/// (all levels, including stdout); such a value round-trips to
26/// `{ min_level: Some(stdout), node_filter }`, which is behaviorally equivalent
27/// to the original rather than exactly equal to it.
28#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, JsonSchema)]
29pub struct LogSubscriptionFilter {
30    /// Minimum log level to receive. `None` means all levels (including stdout).
31    #[schemars(with = "Option<String>")]
32    pub min_level: Option<crate::common::LogLevelOrStdout>,
33    /// Only receive logs from this specific node. `None` means all nodes.
34    pub node_filter: Option<NodeId>,
35}
36
37/// Default queue size when none is configured.
38pub const DEFAULT_QUEUE_SIZE: usize = 10;
39
40/// Queue overflow policy for an input.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
42#[serde(rename_all = "snake_case")]
43pub enum QueuePolicy {
44    /// Drop the oldest queued message when the queue is full (default).
45    #[default]
46    DropOldest,
47    /// Buffer up to 10x `queue_size` without dropping. Drops with ERROR log at hard cap.
48    Backpressure,
49}
50
51impl QueuePolicy {
52    /// Returns the effective capacity for a given configured queue size.
53    ///
54    /// - `DropOldest`: returns `queue_size`, but never less than 1.
55    /// - `Backpressure`: returns `10 * queue_size` (min 100) as a hard safety cap.
56    ///
57    /// A `DropOldest` cap of 0 would drop 100% of the input's events — the
58    /// runtime operator channel sets the just-queued event to `None` on every
59    /// `add_event`, so the operator never receives a single message and the
60    /// dataflow silently hangs. Clamp `queue_size: 0` to 1 (latest-only)
61    /// instead of turning the input into a dead port.
62    ///
63    /// ```
64    /// use dora_message::config::QueuePolicy;
65    ///
66    /// // DropOldest keeps `queue_size`, but never a dead 0-capacity port.
67    /// assert_eq!(QueuePolicy::DropOldest.effective_cap(5), 5);
68    /// assert_eq!(QueuePolicy::DropOldest.effective_cap(0), 1);
69    ///
70    /// // Backpressure buffers 10x the configured size, with a floor of 100.
71    /// assert_eq!(QueuePolicy::Backpressure.effective_cap(5), 100);
72    /// assert_eq!(QueuePolicy::Backpressure.effective_cap(50), 500);
73    /// ```
74    pub fn effective_cap(&self, queue_size: usize) -> usize {
75        match self {
76            Self::DropOldest => queue_size.max(1),
77            Self::Backpressure => queue_size.saturating_mul(10).max(100),
78        }
79    }
80}
81
82/// Contains the input and output configuration of the node.
83#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
84// Same rationale as `descriptor::Node`: these six fields are `#[serde(flatten)]`
85// into `CustomNode`, and `Node` declares the same six keys directly, so they
86// are top-level per-node YAML keys and a seventh I/O key must stay a minor
87// release. Marking this later would itself be the major change, so it cannot
88// wait for the conversion to be convenient. Construct with
89// `NodeRunConfig::default()`; the fields remain `pub`.
90#[non_exhaustive]
91pub struct NodeRunConfig {
92    /// Inputs for the nodes as a map from input ID to `node_id/output_id`.
93    ///
94    /// e.g.
95    ///
96    /// inputs:
97    ///
98    ///   example_input: example_node/example_output1
99    ///
100    #[serde(default)]
101    pub inputs: BTreeMap<DataId, Input>,
102    /// List of output IDs.
103    ///
104    /// e.g.
105    ///
106    /// outputs:
107    ///
108    ///  - output_1
109    ///
110    ///  - output_2
111    #[serde(default)]
112    pub outputs: BTreeSet<DataId>,
113    /// Optional type annotations for outputs
114    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
115    pub output_types: BTreeMap<DataId, String>,
116    /// Per-output framing overrides. Ignored: every output is encoded as
117    /// Arrow IPC (see [`descriptor::OutputFraming`]).
118    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
119    pub output_framing: BTreeMap<DataId, descriptor::OutputFraming>,
120    /// Optional type annotations for inputs
121    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
122    pub input_types: BTreeMap<DataId, String>,
123
124    /// Size of the zenoh shared memory pool for zero-copy output publishing.
125    ///
126    /// Accepts an integer (raw bytes) or a string with a unit suffix
127    /// (`KB`, `MB`, `GB`, case-insensitive).
128    ///
129    /// e.g.
130    ///
131    /// shared_memory_pool_size: 128MB
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub shared_memory_pool_size: Option<ByteSize>,
134}
135
136/// A single input subscription of a node, as declared under `inputs:` in a
137/// dataflow descriptor.
138///
139/// In YAML an input is written either as a bare mapping string
140/// (`source_node/output`) or as a mapping plus per-input options; both forms
141/// deserialize into this struct (see [`InputDef`]).
142#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
143#[serde(from = "InputDef", into = "InputDef")]
144pub struct Input {
145    /// What this input subscribes to (another node's output, a timer, or the
146    /// dataflow log stream).
147    pub mapping: InputMapping,
148    /// Maximum number of buffered messages for this input. `None` uses
149    /// [`DEFAULT_QUEUE_SIZE`].
150    pub queue_size: Option<usize>,
151    /// Deadline, in seconds, after which the input is considered stalled if no
152    /// message arrives. `None` disables the deadline.
153    pub input_timeout: Option<f64>,
154    /// Policy applied when `queue_size` is exceeded. `None` uses the default
155    /// [`QueuePolicy`].
156    pub queue_policy: Option<QueuePolicy>,
157}
158
159impl PartialEq for Input {
160    fn eq(&self, other: &Self) -> bool {
161        self.mapping == other.mapping
162            && self.queue_size == other.queue_size
163            && self.input_timeout.map(f64::to_bits) == other.input_timeout.map(f64::to_bits)
164            && self.queue_policy == other.queue_policy
165    }
166}
167
168impl Eq for Input {}
169
170#[derive(Debug, Clone, Serialize, JsonSchema)]
171#[serde(untagged)]
172pub enum InputDef {
173    MappingOnly(InputMapping),
174    WithOptions {
175        source: InputMapping,
176        #[serde(default, skip_serializing_if = "Option::is_none")]
177        queue_size: Option<usize>,
178        #[serde(default, skip_serializing_if = "Option::is_none")]
179        input_timeout: Option<f64>,
180        #[serde(default, skip_serializing_if = "Option::is_none")]
181        queue_policy: Option<QueuePolicy>,
182    },
183}
184
185impl PartialEq for InputDef {
186    fn eq(&self, other: &Self) -> bool {
187        match (self, other) {
188            (Self::MappingOnly(a), Self::MappingOnly(b)) => a == b,
189            (
190                Self::WithOptions {
191                    source: s1,
192                    queue_size: q1,
193                    input_timeout: t1,
194                    queue_policy: p1,
195                },
196                Self::WithOptions {
197                    source: s2,
198                    queue_size: q2,
199                    input_timeout: t2,
200                    queue_policy: p2,
201                },
202            ) => s1 == s2 && q1 == q2 && t1.map(f64::to_bits) == t2.map(f64::to_bits) && p1 == p2,
203            _ => false,
204        }
205    }
206}
207
208impl Eq for InputDef {}
209
210// Hand-written instead of a derived `untagged` impl: an untagged enum drops
211// every variant's error and reports only "data did not match any variant of
212// untagged enum InputDef", so a dataflow author never saw why a mapping was
213// rejected (e.g. "hz must be a positive finite number", an unknown log level, an
214// invalid node id). A string is the short form, a map the long form; each
215// reports its own error.
216impl<'de> Deserialize<'de> for InputDef {
217    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
218        #[derive(Deserialize)]
219        struct WithOptions {
220            source: InputMapping,
221            #[serde(default)]
222            queue_size: Option<usize>,
223            #[serde(default)]
224            input_timeout: Option<f64>,
225            #[serde(default)]
226            queue_policy: Option<QueuePolicy>,
227        }
228
229        struct Visitor;
230
231        impl<'de> serde::de::Visitor<'de> for Visitor {
232            type Value = InputDef;
233
234            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
235                f.write_str("an input mapping string or a map with a `source` key")
236            }
237
238            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<InputDef, E> {
239                v.parse().map(InputDef::MappingOnly).map_err(E::custom)
240            }
241
242            fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> Result<InputDef, A::Error> {
243                let WithOptions {
244                    source,
245                    queue_size,
246                    input_timeout,
247                    queue_policy,
248                } = WithOptions::deserialize(serde::de::value::MapAccessDeserializer::new(map))?;
249                Ok(InputDef::WithOptions {
250                    source,
251                    queue_size,
252                    input_timeout,
253                    queue_policy,
254                })
255            }
256        }
257
258        deserializer.deserialize_any(Visitor)
259    }
260}
261
262impl From<Input> for InputDef {
263    fn from(input: Input) -> Self {
264        if input.queue_size.is_none()
265            && input.input_timeout.is_none()
266            && input.queue_policy.is_none()
267        {
268            Self::MappingOnly(input.mapping)
269        } else {
270            Self::WithOptions {
271                source: input.mapping,
272                queue_size: input.queue_size,
273                input_timeout: input.input_timeout,
274                queue_policy: input.queue_policy,
275            }
276        }
277    }
278}
279
280impl From<InputDef> for Input {
281    fn from(value: InputDef) -> Self {
282        match value {
283            InputDef::MappingOnly(mapping) => Self {
284                mapping,
285                queue_size: None,
286                input_timeout: None,
287                queue_policy: None,
288            },
289            InputDef::WithOptions {
290                source,
291                queue_size,
292                input_timeout,
293                queue_policy,
294            } => Self {
295                mapping: source,
296                queue_size,
297                input_timeout,
298                queue_policy,
299            },
300        }
301    }
302}
303
304/// The source an [`Input`] subscribes to.
305///
306/// The wire form is a `/`-separated string; [`FromStr`] parses it and
307/// [`fmt::Display`] renders it back, so the two round-trip:
308///
309/// ```
310/// use dora_message::config::InputMapping;
311///
312/// let mapping: InputMapping = "camera/image".parse().unwrap();
313/// assert!(matches!(mapping, InputMapping::User(_)));
314/// assert_eq!(mapping.to_string(), "camera/image");
315///
316/// // Built-in timer source.
317/// let timer: InputMapping = "dora/timer/millis/100".parse().unwrap();
318/// assert_eq!(timer.to_string(), "dora/timer/millis/100");
319///
320/// // A mapping without a `/` separator is rejected.
321/// assert!("no-slash".parse::<InputMapping>().is_err());
322/// ```
323#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
324pub enum InputMapping {
325    /// A built-in timer that fires at a fixed `interval`.
326    ///
327    /// Syntax: `dora/timer/{unit}/{value}`, e.g. `dora/timer/millis/100`.
328    Timer {
329        /// How often the timer fires.
330        interval: Duration,
331    },
332    /// Subscribe to log messages from all (or filtered) nodes in the dataflow.
333    ///
334    /// Syntax: `dora/logs`, `dora/logs/{level}`, `dora/logs/{level}/{node_id}`
335    Logs(LogSubscriptionFilter),
336    /// Subscribe to another node's output — the common case.
337    User(UserInputMapping),
338}
339
340/// `InputMapping` is (de)serialized through [`fmt::Display`]/[`FromStr`], so a
341/// dataflow only ever contains the `/`-separated string, and the schema says
342/// exactly that (#3701). The enum's object shapes never loaded, so they are
343/// not offered as alternatives.
344///
345/// The pattern only asks for a `/`, which is all [`FromStr`] checks before
346/// dispatching on the source. Anything stricter would reject inputs that
347/// `dora` accepts.
348impl JsonSchema for InputMapping {
349    fn schema_name() -> std::borrow::Cow<'static, str> {
350        "InputMapping".into()
351    }
352
353    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
354        schemars::json_schema!({
355            "description": "The source an [`Input`] subscribes to: \
356                `<source>/<output>` for another node's output, \
357                `dora/timer/{unit}/{value}` for a built-in timer, or \
358                `dora/logs[/{level}[/{node_id}]]` for node logs.",
359            "type": "string",
360            "pattern": "/",
361        })
362    }
363}
364
365impl fmt::Display for InputMapping {
366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367        match self {
368            InputMapping::Timer { interval } => {
369                let duration = format_duration(*interval);
370                write!(f, "dora/timer/{duration}")
371            }
372            InputMapping::Logs(filter) => {
373                write!(f, "dora/logs")?;
374                // The wire grammar is `dora/logs/{level}/{node}`, so a node
375                // segment can only follow a level segment. A filter that
376                // restricts the node but leaves `min_level` unset must still
377                // render the node, otherwise the restriction is silently
378                // dropped and the subscription widens to every node (the more
379                // dangerous loss). Render `stdout` in that case: the daemon's
380                // level filter treats a `Stdout` minimum as the most permissive
381                // one (`LogLevelOrStdout::passes` lets every message through
382                // it), so `Some(Stdout)` delivers exactly what `None` does --
383                // all levels, including stdout -- while preserving the node
384                // scope. (`trace` would instead drop the node's stdout lines on
385                // re-parse, the same kind of silent change this guards against.)
386                match (&filter.min_level, &filter.node_filter) {
387                    (Some(level), node_filter) => {
388                        write!(f, "/{}", format_log_level(level))?;
389                        if let Some(node) = node_filter {
390                            write!(f, "/{node}")?;
391                        }
392                    }
393                    (None, Some(node)) => write!(f, "/stdout/{node}")?,
394                    (None, None) => {}
395                }
396                Ok(())
397            }
398            InputMapping::User(mapping) => {
399                write!(f, "{}/{}", mapping.source, mapping.output)
400            }
401        }
402    }
403}
404
405impl FromStr for InputMapping {
406    type Err = String;
407
408    fn from_str(s: &str) -> Result<Self, Self::Err> {
409        let (source, output) = s
410            .split_once('/')
411            .ok_or("input must start with `<source>/`")?;
412
413        let mapping = match source {
414            "dora" => match output.split_once('/') {
415                Some(("timer", output)) => {
416                    let (unit, value) = output.split_once('/').ok_or(
417                        "timer input must specify unit and value (e.g. `secs/5`, `millis/100`, or `hz/30`)",
418                    )?;
419                    let interval = match unit {
420                        "secs" => {
421                            let value = value
422                                .parse()
423                                .map_err(|_| format!("secs must be an integer (got `{value}`)"))?;
424                            Duration::from_secs(value)
425                        }
426                        "millis" => {
427                            let value = value.parse().map_err(|_| {
428                                format!("millis must be an integer (got `{value}`)")
429                            })?;
430                            Duration::from_millis(value)
431                        }
432                        "micros" => {
433                            let value = value.parse().map_err(|_| {
434                                format!("micros must be an integer (got `{value}`)")
435                            })?;
436                            Duration::from_micros(value)
437                        }
438                        "nanos" => {
439                            let value = value
440                                .parse()
441                                .map_err(|_| format!("nanos must be an integer (got `{value}`)"))?;
442                            Duration::from_nanos(value)
443                        }
444                        "hz" => {
445                            let hz: f64 = value.parse().map_err(|_| {
446                                format!("hz must be a positive number (got `{value}`)")
447                            })?;
448                            if !hz.is_finite() || hz <= 0.0 {
449                                return Err(format!(
450                                    "hz must be a positive finite number (got `{value}`)"
451                                ));
452                            }
453                            // A very large hz makes `1/hz` round below 1ns, so
454                            // `try_from_secs_f64` returns `Ok(Duration::ZERO)`;
455                            // that zero interval is caught by the shared guard
456                            // after this `match`, together with `<unit>/0`.
457                            Duration::try_from_secs_f64(1.0 / hz).map_err(|e| {
458                                format!("hz `{value}` produces an out-of-range interval: {e}")
459                            })?
460                        }
461                        other => {
462                            return Err(format!(
463                                "timer unit must be `secs`, `millis`, `micros`, `nanos`, or `hz` (got `{other}`)"
464                            ));
465                        }
466                    };
467                    // A zero-length interval is invalid for every unit: the timer
468                    // task builds `tokio::time::interval(interval)`, which panics
469                    // (`period` must be non-zero). Reject it at parse time for all
470                    // units -- `secs/0`, `millis/0`, `micros/0`, `nanos/0`, and a
471                    // huge `hz` that rounds `1/hz` below 1ns -- so a bad descriptor
472                    // fails at load with a clear message instead of panicking a
473                    // daemon task later.
474                    if interval.is_zero() {
475                        return Err(format!(
476                            "timer interval must be non-zero (`{unit}/{value}` \
477                             produces a zero-length interval)"
478                        ));
479                    }
480                    Self::Timer { interval }
481                }
482                Some(("logs", rest)) => {
483                    // dora/logs/{level} or dora/logs/{level}/{node_id}
484                    let (level_str, node_filter) = match rest.split_once('/') {
485                        Some((level, node)) => {
486                            // Validate the node segment instead of constructing a
487                            // `NodeId` directly: `rest.split_once('/')` keeps every
488                            // slash after the first inside `node`, so an input such
489                            // as `dora/logs/info/a/b` would otherwise build a NodeId
490                            // containing `/` -- a value `validate_node_id` forbids and
491                            // that no real node id can ever equal, silently producing
492                            // a filter that never matches.
493                            let node_id = node.parse::<NodeId>().map_err(|e| e.to_string())?;
494                            (Some(level), Some(node_id))
495                        }
496                        None => {
497                            if rest.is_empty() {
498                                (None, None)
499                            } else {
500                                (Some(rest), None)
501                            }
502                        }
503                    };
504                    let min_level = level_str.map(parse_log_level_str).transpose()?;
505                    Self::Logs(LogSubscriptionFilter {
506                        min_level,
507                        node_filter,
508                    })
509                }
510                Some((other, _)) => {
511                    return Err(format!("unknown dora input `{other}`"));
512                }
513                // "dora/logs" with no sub-path
514                None if output == "logs" => Self::Logs(LogSubscriptionFilter {
515                    min_level: None,
516                    node_filter: None,
517                }),
518                None => return Err("dora input has invalid format".into()),
519            },
520            _ => {
521                // Validate the source/output segments instead of using the
522                // panicking `From<String>` impls (`.into()`): an input mapping
523                // string comes straight from user-authored descriptor YAML, so an
524                // invalid identifier (e.g. containing a space) must surface as a
525                // clean deserialization error rather than panicking the parser.
526                let source = source.parse::<NodeId>().map_err(|e| e.to_string())?;
527                let output = output.parse::<DataId>().map_err(|e| e.to_string())?;
528                Self::User(UserInputMapping { source, output })
529            }
530        };
531
532        Ok(mapping)
533    }
534}
535
536fn parse_log_level_str(s: &str) -> Result<crate::common::LogLevelOrStdout, String> {
537    use crate::common::{LogLevel, LogLevelOrStdout};
538    match s.to_lowercase().as_str() {
539        "stdout" => Ok(LogLevelOrStdout::Stdout),
540        "error" => Ok(LogLevelOrStdout::LogLevel(LogLevel::Error)),
541        "warn" => Ok(LogLevelOrStdout::LogLevel(LogLevel::Warn)),
542        "info" => Ok(LogLevelOrStdout::LogLevel(LogLevel::Info)),
543        "debug" => Ok(LogLevelOrStdout::LogLevel(LogLevel::Debug)),
544        "trace" => Ok(LogLevelOrStdout::LogLevel(LogLevel::Trace)),
545        other => Err(format!(
546            "unknown log level `{other}` (expected: stdout, error, warn, info, debug, trace)"
547        )),
548    }
549}
550
551fn format_log_level(level: &crate::common::LogLevelOrStdout) -> &'static str {
552    use crate::common::{LogLevel, LogLevelOrStdout};
553    match level {
554        LogLevelOrStdout::Stdout => "stdout",
555        LogLevelOrStdout::LogLevel(l) => match *l {
556            LogLevel::Error => "error",
557            LogLevel::Warn => "warn",
558            LogLevel::Info => "info",
559            LogLevel::Debug => "debug",
560            LogLevel::Trace => "trace",
561        },
562    }
563}
564
565/// A [`Duration`] wrapper whose [`Display`](fmt::Display) renders a timer
566/// interval as `<unit>/<count>`, choosing the coarsest unit that represents the
567/// interval *exactly*.
568///
569/// This is the inverse of how a `dora/timer/<unit>/<count>` input is parsed, so
570/// the rendered string round-trips back to the same `Duration`. Picking the
571/// coarsest exact unit matters: rendering a sub-millisecond interval as
572/// `millis/0` would parse back to a zero-length (busy-loop) timer
573/// (dora-rs#2031).
574///
575/// Usually constructed via [`format_duration`].
576///
577/// ```
578/// use std::time::Duration;
579/// use dora_message::config::format_duration;
580///
581/// // Coarsest exact unit is chosen: whole seconds render as `secs`.
582/// assert_eq!(format_duration(Duration::from_secs(2)).to_string(), "secs/2");
583/// assert_eq!(format_duration(Duration::from_millis(100)).to_string(), "millis/100");
584/// // 1500 ms is not a whole number of seconds, so it stays in `millis`.
585/// assert_eq!(format_duration(Duration::from_millis(1500)).to_string(), "millis/1500");
586/// // Sub-millisecond intervals keep their precision instead of truncating to 0.
587/// assert_eq!(format_duration(Duration::from_micros(500)).to_string(), "micros/500");
588/// assert_eq!(format_duration(Duration::from_nanos(333_333)).to_string(), "nanos/333333");
589/// ```
590pub struct FormattedDuration(pub Duration);
591
592impl fmt::Display for FormattedDuration {
593    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
594        // Emit the coarsest unit that represents the interval exactly, so the
595        // value round-trips through `FromStr` without loss. Using `millis` for
596        // sub-millisecond intervals (e.g. `dora/timer/hz/3000` ~= 333µs) would
597        // truncate to `millis/0`, i.e. a 0ms busy-loop interval (dora-rs#2031).
598        let nanos = self.0.as_nanos();
599        if nanos.is_multiple_of(1_000_000_000) {
600            write!(f, "secs/{}", self.0.as_secs())
601        } else if nanos.is_multiple_of(1_000_000) {
602            write!(f, "millis/{}", self.0.as_millis())
603        } else if nanos.is_multiple_of(1_000) {
604            write!(f, "micros/{}", self.0.as_micros())
605        } else {
606            write!(f, "nanos/{nanos}")
607        }
608    }
609}
610
611/// Wrap a [`Duration`] so it renders as a `dora/timer`-style `<unit>/<count>`
612/// string. See [`FormattedDuration`] for the exact formatting rules and a
613/// round-trip example.
614pub fn format_duration(interval: Duration) -> FormattedDuration {
615    FormattedDuration(interval)
616}
617
618impl Serialize for InputMapping {
619    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
620    where
621        S: serde::Serializer,
622    {
623        serializer.collect_str(self)
624    }
625}
626
627impl<'de> Deserialize<'de> for InputMapping {
628    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
629    where
630        D: serde::Deserializer<'de>,
631    {
632        let string = String::deserialize(deserializer)?;
633        string.parse().map_err(serde::de::Error::custom)
634    }
635}
636
637/// A subscription to another node's output, written as `source/output` in YAML.
638#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, JsonSchema)]
639pub struct UserInputMapping {
640    /// The id of the node that produces the output.
641    pub source: NodeId,
642    /// The id of that node's output to subscribe to.
643    pub output: DataId,
644}
645
646/// A byte size that can be deserialized from either an integer (raw bytes) or a
647/// string with a unit suffix (`KB`, `MB`, `GB`, case-insensitive).
648///
649/// Examples: `67108864`, `"64MB"`, `"1 GB"`, `"512kb"`.
650///
651/// Negative, non-finite, and overflowing values are rejected:
652///
653/// ```
654/// use dora_message::config::ByteSize;
655///
656/// assert_eq!("64MB".parse::<ByteSize>().unwrap().as_bytes(), 64 * 1024 * 1024);
657/// assert_eq!("1.5 KB".parse::<ByteSize>().unwrap().as_bytes(), 1536);
658/// assert!("-1KB".parse::<ByteSize>().is_err());
659/// assert!("1TB".parse::<ByteSize>().is_err());
660/// ```
661#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
662pub struct ByteSize(pub usize);
663
664impl ByteSize {
665    /// Returns the size in raw bytes.
666    pub fn as_bytes(&self) -> usize {
667        self.0
668    }
669}
670
671impl FromStr for ByteSize {
672    type Err = String;
673
674    fn from_str(s: &str) -> Result<Self, Self::Err> {
675        let bytes = parse_byte_count(s)?;
676        usize::try_from(bytes)
677            .map(ByteSize)
678            .map_err(|_| format!("byte size `{}` is too large", s.trim()))
679    }
680}
681
682/// Parses a byte size with the same grammar as [`ByteSize`], as a `u64`.
683///
684/// Unlike [`ByteSize`], whose range is `usize`, this accepts sizes of 4 GiB
685/// and above on 32-bit targets. Use it for sizes that describe files or
686/// totals rather than in-memory buffers, e.g. a log file size limit.
687///
688/// ```
689/// assert_eq!(dora_message::config::parse_byte_count("8GB"), Ok(8 << 30));
690/// assert!(dora_message::config::parse_byte_count("-1KB").is_err());
691/// ```
692pub fn parse_byte_count(s: &str) -> Result<u64, String> {
693    let s = s.trim();
694    let (num_part, unit_part) = match s.find(|c: char| c.is_alphabetic()) {
695        Some(pos) => (s[..pos].trim(), s[pos..].trim()),
696        None => {
697            return s.parse().map_err(|_| format!("invalid byte size: `{s}`"));
698        }
699    };
700
701    let multiplier: u64 = match unit_part.to_uppercase().as_str() {
702        "B" => 1,
703        "KB" | "K" => 1024,
704        "MB" | "M" => 1024 * 1024,
705        "GB" | "G" => 1024 * 1024 * 1024,
706        other => return Err(format!("unknown byte size unit: `{other}`")),
707    };
708
709    // Use integer parse when possible to avoid f64 rounding above 2^53.
710    if let Ok(num) = num_part.parse::<u64>() {
711        return num
712            .checked_mul(multiplier)
713            .ok_or_else(|| format!("byte size `{s}` is too large"));
714    }
715
716    let num: f64 = num_part
717        .parse()
718        .map_err(|_| format!("invalid number in byte size: `{num_part}`"))?;
719
720    // Casting a negative or non-finite f64 to u64 saturates (negatives and
721    // NaN to 0, +inf to u64::MAX) instead of erroring, so reject them up
722    // front.
723    if !num.is_finite() || num < 0.0 {
724        return Err(format!(
725            "byte size must be a non-negative, finite number: `{s}`"
726        ));
727    }
728    let bytes = num * multiplier as f64;
729    // `u64::MAX as f64` rounds up to 2^64, and no f64 values exist between
730    // u64::MAX and 2^64, so `>=` rejects exactly the results that exceed
731    // u64::MAX.
732    if bytes >= u64::MAX as f64 {
733        return Err(format!("byte size `{s}` is too large"));
734    }
735    Ok(bytes as u64)
736}
737
738impl fmt::Display for ByteSize {
739    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
740        let bytes = self.0;
741        if bytes == 0 {
742            write!(f, "0B")
743        } else if bytes.is_multiple_of(1024 * 1024 * 1024) {
744            write!(f, "{}GB", bytes / (1024 * 1024 * 1024))
745        } else if bytes.is_multiple_of(1024 * 1024) {
746            write!(f, "{}MB", bytes / (1024 * 1024))
747        } else if bytes.is_multiple_of(1024) {
748            write!(f, "{}KB", bytes / 1024)
749        } else {
750            write!(f, "{bytes}")
751        }
752    }
753}
754
755impl Serialize for ByteSize {
756    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
757    where
758        S: serde::Serializer,
759    {
760        self.0.serialize(serializer)
761    }
762}
763
764impl<'de> Deserialize<'de> for ByteSize {
765    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
766    where
767        D: serde::Deserializer<'de>,
768    {
769        use serde::de;
770
771        struct ByteSizeVisitor;
772
773        impl de::Visitor<'_> for ByteSizeVisitor {
774            type Value = ByteSize;
775
776            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
777                formatter.write_str("a byte size as integer or string (e.g. 67108864, \"64MB\")")
778            }
779
780            fn visit_u64<E: de::Error>(self, v: u64) -> Result<ByteSize, E> {
781                usize::try_from(v)
782                    .map(ByteSize)
783                    .map_err(|_| E::custom(format!("byte size `{v}` is too large")))
784            }
785
786            fn visit_i64<E: de::Error>(self, v: i64) -> Result<ByteSize, E> {
787                if v < 0 {
788                    return Err(E::custom("byte size cannot be negative"));
789                }
790                usize::try_from(v)
791                    .map(ByteSize)
792                    .map_err(|_| E::custom(format!("byte size `{v}` is too large")))
793            }
794
795            fn visit_str<E: de::Error>(self, v: &str) -> Result<ByteSize, E> {
796                v.parse().map_err(E::custom)
797            }
798        }
799
800        deserializer.deserialize_any(ByteSizeVisitor)
801    }
802}
803
804impl JsonSchema for ByteSize {
805    fn schema_name() -> std::borrow::Cow<'static, str> {
806        "ByteSize".into()
807    }
808
809    fn json_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
810        schemars::json_schema!({
811            "anyOf": [
812                { "type": "integer" },
813                { "type": "string" }
814            ],
815            "description": "Byte size: integer (raw bytes) or string with unit (e.g. \"128MB\", \"1GB\")"
816        })
817    }
818}
819
820#[cfg(test)]
821mod tests {
822    use super::*;
823
824    #[test]
825    fn parse_input_without_queue_policy() {
826        let yaml = "source: node_a/output_1\nqueue_size: 5\n";
827        let input: Input = serde_yaml::from_str(yaml).unwrap();
828        assert_eq!(input.queue_size, Some(5));
829        assert_eq!(input.queue_policy, None);
830    }
831
832    #[test]
833    fn drop_oldest_cap_is_never_zero() {
834        // A `queue_size: 0` DropOldest input must keep at least the latest
835        // message; a cap of 0 would starve the operator entirely.
836        assert_eq!(QueuePolicy::DropOldest.effective_cap(0), 1);
837        // Non-zero sizes are unchanged.
838        assert_eq!(QueuePolicy::DropOldest.effective_cap(1), 1);
839        assert_eq!(QueuePolicy::DropOldest.effective_cap(5), 5);
840    }
841
842    #[test]
843    fn backpressure_cap_has_floor() {
844        assert_eq!(QueuePolicy::Backpressure.effective_cap(0), 100);
845        assert_eq!(QueuePolicy::Backpressure.effective_cap(5), 100);
846        assert_eq!(QueuePolicy::Backpressure.effective_cap(20), 200);
847    }
848
849    #[test]
850    fn parse_user_mapping_rejects_invalid_ids() {
851        // A source node id with a space is not a valid `NodeId` and must be
852        // rejected with a clean error rather than panicking the parser via the
853        // `From<String>` impl.
854        let result: Result<InputMapping, _> = "bad node/output".parse();
855        assert!(result.is_err(), "invalid source node id must be rejected");
856
857        // An output data id with an invalid character must likewise be rejected.
858        let result: Result<InputMapping, _> = "node_a/bad output".parse();
859        assert!(result.is_err(), "invalid output data id must be rejected");
860
861        // A valid mapping still parses successfully.
862        let mapping: InputMapping = "node_a/output_1".parse().unwrap();
863        assert!(matches!(mapping, InputMapping::User(_)));
864    }
865
866    /// An invalid mapping must report why it was rejected, in both the
867    /// short and the long form, not serde's generic "data did not match any
868    /// variant of untagged enum InputDef".
869    #[test]
870    fn invalid_input_mapping_reports_its_own_error() {
871        for (yaml, expected) in [
872            ("dora/timer/hz/0", "positive finite"),
873            ("source: dora/timer/hz/0", "positive finite"),
874            ("bad node/output", "invalid character"),
875            (
876                "source: bad node/output\nqueue_size: 2",
877                "invalid character",
878            ),
879        ] {
880            let err = serde_yaml::from_str::<Input>(yaml).unwrap_err().to_string();
881            assert!(
882                err.contains(expected) && !err.contains("did not match any variant"),
883                "yaml {yaml:?}: {err}"
884            );
885        }
886        // Neither a string nor a map: the expectation names both forms.
887        let err = serde_yaml::from_str::<Input>("42").unwrap_err().to_string();
888        assert!(err.contains("input mapping string"), "{err}");
889    }
890
891    /// The JSON wire form (CLI -> coordinator -> daemon) still parses.
892    #[test]
893    fn input_round_trips_through_json() {
894        for yaml in ["node_a/output_1", "source: node_a/output_1\nqueue_size: 3"] {
895            let input: Input = serde_yaml::from_str(yaml).unwrap();
896            let json = serde_json::to_string(&input).unwrap();
897            assert_eq!(serde_json::from_str::<Input>(&json).unwrap(), input);
898        }
899    }
900
901    #[test]
902    fn parse_input_with_drop_oldest_policy() {
903        let yaml = "source: node_a/output_1\nqueue_size: 5\nqueue_policy: drop_oldest\n";
904        let input: Input = serde_yaml::from_str(yaml).unwrap();
905        assert_eq!(input.queue_policy, Some(QueuePolicy::DropOldest));
906    }
907
908    #[test]
909    fn parse_input_with_backpressure_policy() {
910        let yaml = "source: node_a/output_1\nqueue_size: 10\nqueue_policy: backpressure\n";
911        let input: Input = serde_yaml::from_str(yaml).unwrap();
912        assert_eq!(input.queue_policy, Some(QueuePolicy::Backpressure));
913    }
914
915    #[test]
916    fn parse_short_form_input_has_no_policy() {
917        let yaml = "node_a/output_1";
918        let input: Input = serde_yaml::from_str(yaml).unwrap();
919        assert_eq!(input.queue_policy, None);
920        assert_eq!(input.queue_size, None);
921    }
922
923    #[test]
924    fn roundtrip_input_with_policy() {
925        let input = Input {
926            mapping: "node_a/output_1".parse().unwrap(),
927            queue_size: Some(3),
928            input_timeout: None,
929            queue_policy: Some(QueuePolicy::Backpressure),
930        };
931        let yaml = serde_yaml::to_string(&input).unwrap();
932        let parsed: Input = serde_yaml::from_str(&yaml).unwrap();
933        assert_eq!(input, parsed);
934    }
935
936    /// Regression tests for dora-rs/adora#144: `dora/timer/hz/N` is
937    /// documented across README, guide, schema, and real examples
938    /// (`streaming-example`, `dynamic-agent-tools`) but the parser
939    /// previously only accepted `secs` / `millis`.
940    #[test]
941    fn parse_timer_hz_integer() {
942        let mapping: InputMapping = "dora/timer/hz/30".parse().unwrap();
943        match mapping {
944            InputMapping::Timer { interval } => {
945                // 1 / 30 Hz ≈ 33.333 ms
946                assert_eq!(interval, Duration::from_secs_f64(1.0 / 30.0));
947            }
948            other => panic!("expected Timer, got {other:?}"),
949        }
950    }
951
952    #[test]
953    fn parse_timer_hz_fractional() {
954        // Used in examples/streaming-example/dataflow.yml
955        let mapping: InputMapping = "dora/timer/hz/0.5".parse().unwrap();
956        match mapping {
957            InputMapping::Timer { interval } => {
958                assert_eq!(interval, Duration::from_secs(2));
959            }
960            other => panic!("expected Timer, got {other:?}"),
961        }
962    }
963
964    #[test]
965    fn parse_timer_hz_rejects_zero() {
966        let err = "dora/timer/hz/0".parse::<InputMapping>().unwrap_err();
967        assert!(err.contains("hz"), "error should mention hz: {err}");
968    }
969
970    #[test]
971    fn parse_timer_hz_rejects_negative() {
972        let err = "dora/timer/hz/-1".parse::<InputMapping>().unwrap_err();
973        assert!(err.contains("hz"), "error should mention hz: {err}");
974    }
975
976    #[test]
977    fn parse_timer_hz_rejects_non_numeric() {
978        let err = "dora/timer/hz/foo".parse::<InputMapping>().unwrap_err();
979        assert!(err.contains("hz"), "error should mention hz: {err}");
980    }
981
982    #[test]
983    fn parse_timer_hz_rejects_overflow() {
984        // A pathologically small hz makes 1/hz overflow Duration; this must
985        // return an error, not panic (was `Duration::from_secs_f64`, which
986        // panics on out-of-range input).
987        let err = "dora/timer/hz/0.00000000000000000001"
988            .parse::<InputMapping>()
989            .unwrap_err();
990        assert!(err.contains("hz"), "error should mention hz: {err}");
991    }
992
993    #[test]
994    fn parse_timer_rejects_zero_interval_for_every_unit() {
995        // A zero-length interval panics `tokio::time::interval` in the timer
996        // task (`period` must be non-zero), so every unit that can express it
997        // must be rejected at parse time -- not just `hz`. `<unit>/0` is the
998        // obvious case; a huge `hz` reaches the same zero interval because
999        // `1/hz` rounds below 1ns.
1000        let cases = [
1001            "dora/timer/secs/0",
1002            "dora/timer/millis/0",
1003            "dora/timer/micros/0",
1004            "dora/timer/nanos/0",
1005            "dora/timer/hz/1000000000000",
1006        ];
1007        for case in cases {
1008            let err = case.parse::<InputMapping>().unwrap_err();
1009            assert!(
1010                err.contains("non-zero"),
1011                "`{case}` should be rejected as a zero-length interval, got: {err}"
1012            );
1013        }
1014        // Sanity check: the huge-hz conversion really does round to zero.
1015        assert_eq!(
1016            Duration::try_from_secs_f64(1.0 / 1_000_000_000_000.0),
1017            Ok(Duration::ZERO)
1018        );
1019    }
1020
1021    /// Regression test for dora-rs#2031: the `Display` impl previously emitted
1022    /// `millis/0` (or `secs/0`) for any sub-millisecond interval, so a valid
1023    /// high-rate timer like `dora/timer/hz/3000` (~=333µs) round-tripped into a
1024    /// 0ms busy-loop interval. Sub-ms intervals must survive Display -> parse.
1025    #[test]
1026    fn timer_subms_interval_roundtrips() {
1027        let cases = [
1028            "dora/timer/hz/3000",  // ~= 333_333 ns, not a whole µs
1029            "dora/timer/micros/1", // 1µs
1030            "dora/timer/nanos/1",  // 1ns
1031            "dora/timer/nanos/500",
1032            "dora/timer/micros/250",
1033        ];
1034        for case in cases {
1035            let mapping: InputMapping = case.parse().unwrap();
1036            let InputMapping::Timer { interval } = mapping else {
1037                panic!("expected Timer for `{case}`, got {mapping:?}");
1038            };
1039            assert!(!interval.is_zero(), "`{case}` parsed to a zero interval");
1040            let rendered = mapping.to_string();
1041            let reparsed: InputMapping = rendered.parse().unwrap();
1042            assert_eq!(
1043                mapping, reparsed,
1044                "`{case}` did not round-trip (rendered as `{rendered}`)"
1045            );
1046        }
1047    }
1048
1049    #[test]
1050    fn timer_display_uses_coarsest_exact_unit() {
1051        let render = |d: Duration| format_duration(d).to_string();
1052        assert_eq!(render(Duration::from_secs(5)), "secs/5");
1053        assert_eq!(render(Duration::from_millis(100)), "millis/100");
1054        assert_eq!(render(Duration::from_micros(250)), "micros/250");
1055        assert_eq!(render(Duration::from_nanos(500)), "nanos/500");
1056        // 1/3000 Hz = 333_333 ns (not a whole microsecond) -> nanos.
1057        assert_eq!(render(Duration::from_nanos(333_333)), "nanos/333333");
1058    }
1059
1060    #[test]
1061    fn parse_timer_micros_and_nanos() {
1062        let micros: InputMapping = "dora/timer/micros/250".parse().unwrap();
1063        assert_eq!(
1064            micros,
1065            InputMapping::Timer {
1066                interval: Duration::from_micros(250)
1067            }
1068        );
1069        let nanos: InputMapping = "dora/timer/nanos/500".parse().unwrap();
1070        assert_eq!(
1071            nanos,
1072            InputMapping::Timer {
1073                interval: Duration::from_nanos(500)
1074            }
1075        );
1076    }
1077
1078    #[test]
1079    fn timer_whole_second_and_milli_still_roundtrip() {
1080        for case in ["dora/timer/secs/2", "dora/timer/millis/100"] {
1081            let mapping: InputMapping = case.parse().unwrap();
1082            let reparsed: InputMapping = mapping.to_string().parse().unwrap();
1083            assert_eq!(mapping, reparsed);
1084        }
1085        // Whole seconds/millis still render with their original unit.
1086        assert_eq!(
1087            "dora/timer/secs/2"
1088                .parse::<InputMapping>()
1089                .unwrap()
1090                .to_string(),
1091            "dora/timer/secs/2"
1092        );
1093        assert_eq!(
1094            "dora/timer/millis/100"
1095                .parse::<InputMapping>()
1096                .unwrap()
1097                .to_string(),
1098            "dora/timer/millis/100"
1099        );
1100    }
1101
1102    #[test]
1103    fn roundtrip_input_without_policy_uses_short_form() {
1104        let input = Input {
1105            mapping: "node_a/output_1".parse().unwrap(),
1106            queue_size: None,
1107            input_timeout: None,
1108            queue_policy: None,
1109        };
1110        let yaml = serde_yaml::to_string(&input).unwrap();
1111        // Short form should not contain "source:" key
1112        assert!(!yaml.contains("source:"));
1113        let parsed: Input = serde_yaml::from_str(&yaml).unwrap();
1114        assert_eq!(input, parsed);
1115    }
1116
1117    #[test]
1118    fn queue_policy_default_is_drop_oldest() {
1119        assert_eq!(QueuePolicy::default(), QueuePolicy::DropOldest);
1120    }
1121
1122    #[test]
1123    fn parse_logs_all() {
1124        let mapping: InputMapping = "dora/logs".parse().unwrap();
1125        assert!(matches!(
1126            mapping,
1127            InputMapping::Logs(LogSubscriptionFilter {
1128                min_level: None,
1129                node_filter: None,
1130            })
1131        ));
1132    }
1133
1134    #[test]
1135    fn parse_logs_with_level() {
1136        use crate::common::{LogLevel, LogLevelOrStdout};
1137        let mapping: InputMapping = "dora/logs/info".parse().unwrap();
1138        match mapping {
1139            InputMapping::Logs(f) => {
1140                assert_eq!(
1141                    f.min_level,
1142                    Some(LogLevelOrStdout::LogLevel(LogLevel::Info))
1143                );
1144                assert_eq!(f.node_filter, None);
1145            }
1146            _ => panic!("expected Logs variant"),
1147        }
1148    }
1149
1150    #[test]
1151    fn parse_logs_with_level_and_node() {
1152        use crate::common::{LogLevel, LogLevelOrStdout};
1153        let mapping: InputMapping = "dora/logs/error/sensor".parse().unwrap();
1154        match mapping {
1155            InputMapping::Logs(f) => {
1156                assert_eq!(
1157                    f.min_level,
1158                    Some(LogLevelOrStdout::LogLevel(LogLevel::Error))
1159                );
1160                assert_eq!(f.node_filter, Some(NodeId("sensor".to_string())));
1161            }
1162            _ => panic!("expected Logs variant"),
1163        }
1164    }
1165
1166    #[test]
1167    fn parse_logs_invalid_level() {
1168        let result: Result<InputMapping, _> = "dora/logs/banana".parse();
1169        assert!(result.is_err());
1170    }
1171
1172    #[test]
1173    fn parse_logs_rejects_invalid_node_filter() {
1174        // A node segment with an extra `/` (kept by `split_once`) is not a valid
1175        // NodeId and must be rejected rather than silently yielding a filter that
1176        // can never match a real (validated) node id.
1177        let result: Result<InputMapping, _> = "dora/logs/info/a/b".parse();
1178        assert!(result.is_err(), "node filter `a/b` must be rejected");
1179
1180        // A node segment containing a space is likewise invalid.
1181        let result: Result<InputMapping, _> = "dora/logs/info/bad node".parse();
1182        assert!(result.is_err(), "node filter `bad node` must be rejected");
1183    }
1184
1185    #[test]
1186    fn display_roundtrip_logs_all() {
1187        let mapping: InputMapping = "dora/logs".parse().unwrap();
1188        assert_eq!(mapping.to_string(), "dora/logs");
1189    }
1190
1191    #[test]
1192    fn display_roundtrip_logs_with_level() {
1193        let mapping: InputMapping = "dora/logs/warn".parse().unwrap();
1194        assert_eq!(mapping.to_string(), "dora/logs/warn");
1195    }
1196
1197    #[test]
1198    fn display_roundtrip_logs_with_level_and_node() {
1199        let mapping: InputMapping = "dora/logs/debug/camera".parse().unwrap();
1200        assert_eq!(mapping.to_string(), "dora/logs/debug/camera");
1201    }
1202
1203    #[test]
1204    fn display_logs_node_without_level_keeps_node() {
1205        use crate::common::LogLevelOrStdout;
1206
1207        // `{ min_level: None, node_filter: Some(_) }` is not producible via
1208        // `FromStr` but is freely constructible directly. `Display` must not
1209        // drop the node restriction (which would silently widen the
1210        // subscription to every node); it renders the `stdout` level, which the
1211        // daemon's filter treats as the most permissive one, so the node stays
1212        // in the output without changing which messages are delivered.
1213        let filter = InputMapping::Logs(LogSubscriptionFilter {
1214            min_level: None,
1215            node_filter: Some("mynode".parse().unwrap()),
1216        });
1217        assert_eq!(filter.to_string(), "dora/logs/stdout/mynode");
1218
1219        // The rendered form parses back to the node-scoped filter at `stdout`,
1220        // which is behaviorally equivalent to `None` (all levels pass), and is
1221        // idempotent afterwards.
1222        let round: InputMapping = filter.to_string().parse().unwrap();
1223        assert_eq!(
1224            round,
1225            InputMapping::Logs(LogSubscriptionFilter {
1226                min_level: Some(LogLevelOrStdout::Stdout),
1227                node_filter: Some("mynode".parse().unwrap()),
1228            })
1229        );
1230        assert_eq!(round.to_string(), "dora/logs/stdout/mynode");
1231    }
1232
1233    #[test]
1234    fn parse_logs_trailing_slash() {
1235        let mapping: InputMapping = "dora/logs/".parse().unwrap();
1236        assert!(matches!(
1237            mapping,
1238            InputMapping::Logs(LogSubscriptionFilter {
1239                min_level: None,
1240                node_filter: None,
1241            })
1242        ));
1243    }
1244
1245    #[test]
1246    fn byte_size_parses_raw_bytes() {
1247        assert_eq!("1024".parse::<ByteSize>().unwrap(), ByteSize(1024));
1248        assert_eq!("0".parse::<ByteSize>().unwrap(), ByteSize(0));
1249    }
1250
1251    #[test]
1252    fn byte_size_parses_units_case_insensitively() {
1253        assert_eq!("1KB".parse::<ByteSize>().unwrap(), ByteSize(1024));
1254        assert_eq!("1kb".parse::<ByteSize>().unwrap(), ByteSize(1024));
1255        assert_eq!("1MB".parse::<ByteSize>().unwrap(), ByteSize(1024 * 1024));
1256        assert_eq!(
1257            "1GB".parse::<ByteSize>().unwrap(),
1258            ByteSize(1024 * 1024 * 1024)
1259        );
1260        assert_eq!(
1261            "128 MB".parse::<ByteSize>().unwrap(),
1262            ByteSize(128 * 1024 * 1024)
1263        );
1264        assert_eq!("512B".parse::<ByteSize>().unwrap(), ByteSize(512));
1265    }
1266
1267    #[test]
1268    fn byte_size_rejects_unknown_unit() {
1269        assert!("1TB".parse::<ByteSize>().is_err());
1270        assert!("abc".parse::<ByteSize>().is_err());
1271    }
1272
1273    #[test]
1274    fn byte_size_rejects_negative() {
1275        // Negative f64 → usize casts saturate to 0, so without an explicit
1276        // check `-1KB` silently parsed as a zero-byte pool size.
1277        assert!("-1KB".parse::<ByteSize>().is_err());
1278        assert!("-0.5MB".parse::<ByteSize>().is_err());
1279        assert!("-1".parse::<ByteSize>().is_err());
1280        // The integer deserialize path already rejected negatives; the string
1281        // path must agree.
1282        assert!(serde_yaml::from_str::<ByteSize>("-1").is_err());
1283        assert!(serde_yaml::from_str::<ByteSize>(r#""-1KB""#).is_err());
1284    }
1285
1286    #[test]
1287    fn byte_size_rejects_overflow() {
1288        // f64 path: finite but larger than usize::MAX must error, not
1289        // saturate silently.
1290        assert!("99999999999999999999999GB".parse::<ByteSize>().is_err());
1291        // Integer path: checked_mul must catch the overflow.
1292        assert!(format!("{}KB", usize::MAX).parse::<ByteSize>().is_err());
1293        // Exactly 2^64 (= 2^54 * 1024) on the float path: `usize::MAX as f64`
1294        // rounds up to 2^64, so a `>` comparison would let this saturate to
1295        // usize::MAX silently.
1296        assert!("18014398509481984.0KB".parse::<ByteSize>().is_err());
1297    }
1298
1299    #[test]
1300    fn byte_size_integer_values_parse_exactly() {
1301        // 2^53 + 1 is not representable as f64; the integer fast path must
1302        // preserve it exactly (mirrors dora-core's parse_byte_size).
1303        assert_eq!(
1304            "9007199254740993B".parse::<ByteSize>().unwrap(),
1305            ByteSize(9007199254740993)
1306        );
1307    }
1308
1309    #[test]
1310    fn byte_size_float_path_still_works() {
1311        assert_eq!("1.5KB".parse::<ByteSize>().unwrap(), ByteSize(1536));
1312        assert_eq!("0.5MB".parse::<ByteSize>().unwrap(), ByteSize(512 * 1024));
1313        assert!("x.5KB".parse::<ByteSize>().is_err());
1314    }
1315
1316    #[test]
1317    fn byte_size_deserializes_int_or_string() {
1318        let from_int: ByteSize = serde_yaml::from_str("67108864").unwrap();
1319        assert_eq!(from_int, ByteSize(64 * 1024 * 1024));
1320
1321        let from_str: ByteSize = serde_yaml::from_str(r#""64MB""#).unwrap();
1322        assert_eq!(from_str, ByteSize(64 * 1024 * 1024));
1323    }
1324
1325    #[test]
1326    fn byte_size_serializes_as_integer() {
1327        let yaml = serde_yaml::to_string(&ByteSize(1024)).unwrap();
1328        assert_eq!(yaml.trim(), "1024");
1329    }
1330
1331    #[test]
1332    fn byte_size_display_uses_largest_exact_unit() {
1333        assert_eq!(ByteSize(1024).to_string(), "1KB");
1334        assert_eq!(ByteSize(1024 * 1024).to_string(), "1MB");
1335        assert_eq!(ByteSize(2 * 1024 * 1024 * 1024).to_string(), "2GB");
1336        assert_eq!(ByteSize(1500).to_string(), "1500");
1337    }
1338
1339    #[test]
1340    fn node_run_config_parses_shared_memory_pool_size() {
1341        let yaml = "shared_memory_pool_size: 128MB\n";
1342        let config: NodeRunConfig = serde_yaml::from_str(yaml).unwrap();
1343        assert_eq!(
1344            config.shared_memory_pool_size,
1345            Some(ByteSize(128 * 1024 * 1024))
1346        );
1347    }
1348
1349    #[test]
1350    fn node_run_config_shared_memory_pool_size_optional() {
1351        let yaml = "outputs:\n  - foo\n";
1352        let config: NodeRunConfig = serde_yaml::from_str(yaml).unwrap();
1353        assert_eq!(config.shared_memory_pool_size, None);
1354    }
1355
1356    // #3701: inputs are strings in YAML, so the schema describes only the
1357    // string, and its pattern has to agree with what `FromStr` accepts.
1358    #[test]
1359    fn input_mapping_schema_is_the_string_form() {
1360        let schema = serde_json::to_value(schemars::schema_for!(InputMapping)).unwrap();
1361        assert_eq!(schema["type"], "string");
1362        assert_eq!(schema["pattern"], "/");
1363        assert!(schema.get("oneOf").is_none(), "{schema}");
1364
1365        for valid in ["camera/image", "dora/timer/millis/100", "dora/logs"] {
1366            assert!(valid.parse::<InputMapping>().is_ok(), "{valid}");
1367            assert!(valid.contains('/'), "{valid} should match the pattern");
1368        }
1369        assert!("no-slash".parse::<InputMapping>().is_err());
1370    }
1371}