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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, JsonSchema)]
29pub struct LogSubscriptionFilter {
30 #[schemars(with = "Option<String>")]
32 pub min_level: Option<crate::common::LogLevelOrStdout>,
33 pub node_filter: Option<NodeId>,
35}
36
37pub const DEFAULT_QUEUE_SIZE: usize = 10;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
42#[serde(rename_all = "snake_case")]
43pub enum QueuePolicy {
44 #[default]
46 DropOldest,
47 Backpressure,
49}
50
51impl QueuePolicy {
52 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
84#[non_exhaustive]
91pub struct NodeRunConfig {
92 #[serde(default)]
101 pub inputs: BTreeMap<DataId, Input>,
102 #[serde(default)]
112 pub outputs: BTreeSet<DataId>,
113 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
115 pub output_types: BTreeMap<DataId, String>,
116 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
119 pub output_framing: BTreeMap<DataId, descriptor::OutputFraming>,
120 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
122 pub input_types: BTreeMap<DataId, String>,
123
124 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub shared_memory_pool_size: Option<ByteSize>,
134}
135
136#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
143#[serde(from = "InputDef", into = "InputDef")]
144pub struct Input {
145 pub mapping: InputMapping,
148 pub queue_size: Option<usize>,
151 pub input_timeout: Option<f64>,
154 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
210impl<'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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
324pub enum InputMapping {
325 Timer {
329 interval: Duration,
331 },
332 Logs(LogSubscriptionFilter),
336 User(UserInputMapping),
338}
339
340impl 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 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 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 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 let (level_str, node_filter) = match rest.split_once('/') {
485 Some((level, node)) => {
486 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 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 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
565pub struct FormattedDuration(pub Duration);
591
592impl fmt::Display for FormattedDuration {
593 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
594 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
611pub 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, JsonSchema)]
639pub struct UserInputMapping {
640 pub source: NodeId,
642 pub output: DataId,
644}
645
646#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
662pub struct ByteSize(pub usize);
663
664impl ByteSize {
665 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
682pub 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 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 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 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 assert_eq!(QueuePolicy::DropOldest.effective_cap(0), 1);
837 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 let result: Result<InputMapping, _> = "bad node/output".parse();
855 assert!(result.is_err(), "invalid source node id must be rejected");
856
857 let result: Result<InputMapping, _> = "node_a/bad output".parse();
859 assert!(result.is_err(), "invalid output data id must be rejected");
860
861 let mapping: InputMapping = "node_a/output_1".parse().unwrap();
863 assert!(matches!(mapping, InputMapping::User(_)));
864 }
865
866 #[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 let err = serde_yaml::from_str::<Input>("42").unwrap_err().to_string();
888 assert!(err.contains("input mapping string"), "{err}");
889 }
890
891 #[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 #[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 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 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 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 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 assert_eq!(
1016 Duration::try_from_secs_f64(1.0 / 1_000_000_000_000.0),
1017 Ok(Duration::ZERO)
1018 );
1019 }
1020
1021 #[test]
1026 fn timer_subms_interval_roundtrips() {
1027 let cases = [
1028 "dora/timer/hz/3000", "dora/timer/micros/1", "dora/timer/nanos/1", "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 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 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 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 let result: Result<InputMapping, _> = "dora/logs/info/a/b".parse();
1178 assert!(result.is_err(), "node filter `a/b` must be rejected");
1179
1180 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 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 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 assert!("-1KB".parse::<ByteSize>().is_err());
1278 assert!("-0.5MB".parse::<ByteSize>().is_err());
1279 assert!("-1".parse::<ByteSize>().is_err());
1280 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 assert!("99999999999999999999999GB".parse::<ByteSize>().is_err());
1291 assert!(format!("{}KB", usize::MAX).parse::<ByteSize>().is_err());
1293 assert!("18014398509481984.0KB".parse::<ByteSize>().is_err());
1297 }
1298
1299 #[test]
1300 fn byte_size_integer_values_parse_exactly() {
1301 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 #[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}