Skip to main content

dora_message/
common.rs

1use core::fmt;
2use std::{borrow::Cow, collections::BTreeMap};
3
4use aligned_vec::{AVec, ConstAlign};
5use chrono::{DateTime, Utc};
6use eyre::Context as _;
7use serde::Deserialize;
8use uuid::Uuid;
9
10use crate::{BuildId, DataflowId, daemon_to_daemon::InterDaemonEvent, id::NodeId};
11
12pub use log::Level as LogLevel;
13
14/// [`LogMessage::fields`] key of the notice the coordinator sends a log
15/// reader that fell behind; the value is how many lines it missed. Clients
16/// show such a notice even when they filter the stream by node or pattern.
17pub const DROPPED_LOG_LINES_FIELD: &str = "dora_dropped_log_lines";
18
19/// A single log record delivered to `dora/logs` subscribers.
20///
21/// One of these is produced for every captured log line — a `tracing` event
22/// from a dora component or a line a node wrote to stdout/stderr — and carries
23/// both the message and the routing/provenance context a log consumer needs to
24/// attribute it (which dataflow, node, and daemon it came from).
25#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
26#[must_use]
27pub struct LogMessage {
28    /// The build this record belongs to, when it originated during a build.
29    pub build_id: Option<BuildId>,
30    /// The dataflow the emitting component was part of, if any.
31    pub dataflow_id: Option<DataflowId>,
32    /// The node that emitted the record, if it came from a node.
33    pub node_id: Option<NodeId>,
34    /// The daemon that captured and forwarded the record.
35    pub daemon_id: Option<DaemonId>,
36    /// The severity, or [`LogLevelOrStdout::Stdout`] for a captured stdout line.
37    pub level: LogLevelOrStdout,
38    /// The `tracing` target (typically the emitting module path), when known.
39    pub target: Option<String>,
40    /// Source module path of the emitting code, when known.
41    pub module_path: Option<String>,
42    /// Source file of the emitting code, when known.
43    pub file: Option<String>,
44    /// Line within [`file`](Self::file) of the emitting code, when known.
45    pub line: Option<u32>,
46    /// The log text itself.
47    pub message: String,
48    /// When the record was produced.
49    pub timestamp: DateTime<Utc>,
50    /// Structured key/value fields attached to a `tracing` event, if any.
51    pub fields: Option<BTreeMap<String, String>>,
52}
53
54#[derive(Deserialize)]
55pub struct LogMessageHelper {
56    build_id: Option<BuildId>,
57    dataflow_id: Option<DataflowId>,
58    node_id: Option<NodeId>,
59    daemon_id: Option<DaemonId>,
60    level: LogLevelOrStdout,
61    target: Option<String>,
62    module_path: Option<String>,
63    file: Option<String>,
64    line: Option<u32>,
65    message: Option<String>,
66    timestamp: DateTime<Utc>,
67    #[serde(default, deserialize_with = "deserialize_stringified_fields")]
68    fields: Option<BTreeMap<String, String>>,
69}
70
71/// Read a `tracing` JSON `fields` object, turning every non-string value into
72/// its JSON text.
73///
74/// `tracing-subscriber`'s JSON formatter writes a numeric or boolean field
75/// (`info!(frame = 42, "got frame")`) as a JSON number or bool, not a string.
76/// Requiring strings here made the whole line fail to parse, so the daemon
77/// fell back to treating it as raw `stdout` text — which loses its level and
78/// drops it entirely under any `min_log_level` or `dora/logs/<level>` filter.
79fn deserialize_stringified_fields<'de, D>(
80    deserializer: D,
81) -> Result<Option<BTreeMap<String, String>>, D::Error>
82where
83    D: serde::Deserializer<'de>,
84{
85    let fields = Option::<BTreeMap<String, serde_json::Value>>::deserialize(deserializer)?;
86    Ok(fields.map(|fields| {
87        fields
88            .into_iter()
89            .map(|(key, value)| {
90                let value = match value {
91                    serde_json::Value::String(s) => s,
92                    other => other.to_string(),
93                };
94                (key, value)
95            })
96            .collect()
97    }))
98}
99
100impl From<LogMessageHelper> for LogMessage {
101    fn from(helper: LogMessageHelper) -> Self {
102        let fields = helper.fields.as_ref();
103        // Use `or_else` throughout so each fallback (a `BTreeMap` lookup plus a
104        // `String` clone, and sometimes a parse) is computed only when the
105        // typed field is absent. `or` would evaluate every fallback eagerly and
106        // discard it whenever the typed field is already `Some`.
107        LogMessage {
108            build_id: helper.build_id.or_else(|| {
109                fields
110                    .and_then(|f| f.get("build_id").cloned())
111                    .and_then(|id| BuildId::from_display_str(&id))
112            }),
113            dataflow_id: helper.dataflow_id.or_else(|| {
114                fields
115                    .and_then(|f| f.get("dataflow_id").cloned())
116                    .and_then(|id| Uuid::parse_str(&id).ok())
117            }),
118            node_id: helper.node_id.or_else(|| {
119                fields
120                    .and_then(|f| f.get("node_id").cloned())
121                    .and_then(|id| id.parse::<NodeId>().ok())
122            }),
123            daemon_id: helper.daemon_id.or_else(|| {
124                fields
125                    .and_then(|f| f.get("daemon_id").cloned())
126                    .and_then(|id| DaemonId::from_display_str(&id))
127            }),
128            level: helper.level,
129            target: helper
130                .target
131                .or_else(|| fields.and_then(|f| f.get("target").cloned())),
132            module_path: helper
133                .module_path
134                .or_else(|| fields.and_then(|f| f.get("module_path").cloned())),
135            file: helper
136                .file
137                .or_else(|| fields.and_then(|f| f.get("file").cloned())),
138            line: helper.line.or_else(|| {
139                fields
140                    .and_then(|f| f.get("line").cloned())
141                    .and_then(|s| s.parse().ok())
142            }),
143            message: helper
144                .message
145                .or_else(|| fields.and_then(|f| f.get("message").cloned()))
146                .unwrap_or_default(),
147            fields: helper.fields,
148            timestamp: helper.timestamp,
149        }
150    }
151}
152
153#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, PartialOrd, Ord)]
154#[serde(rename_all = "UPPERCASE")]
155pub enum LogLevelOrStdout {
156    #[serde(rename = "stdout")]
157    Stdout,
158    #[serde(untagged)]
159    LogLevel(LogLevel),
160}
161
162impl LogLevelOrStdout {
163    /// Returns true if a message at this level passes the given minimum level filter.
164    ///
165    /// `Stdout` is treated as a distinct channel rather than a severity, so it
166    /// does not participate in the `Error < Warn < Info < Debug < Trace`
167    /// ordering (where `Error` is the most severe and `Trace` the least):
168    ///
169    /// - A `Stdout` message passes only a `Stdout` filter; it is never
170    ///   delivered to a severity filter.
171    /// - A `LogLevel` message always passes a `Stdout` filter (the most
172    ///   permissive), and passes a `LogLevel` filter `min` when its severity is
173    ///   at least as severe as `min` (`msg <= min` in log-crate ordering).
174    ///
175    /// ```
176    /// use dora_message::common::{LogLevel, LogLevelOrStdout};
177    ///
178    /// let stdout = LogLevelOrStdout::Stdout;
179    /// let info = LogLevelOrStdout::LogLevel(LogLevel::Info);
180    /// let error = LogLevelOrStdout::LogLevel(LogLevel::Error);
181    ///
182    /// // Severity: `Error` is more severe than `Info`, so it passes an `Info` filter...
183    /// assert!(error.passes(&info));
184    /// // ...while a less severe message is filtered out.
185    /// assert!(!info.passes(&error));
186    /// // A message passes a filter at its own level.
187    /// assert!(info.passes(&info));
188    ///
189    /// // A `LogLevel` message always passes the (most permissive) `Stdout` filter,
190    /// // but a `Stdout` message passes only a `Stdout` filter, never a severity one.
191    /// assert!(info.passes(&stdout));
192    /// assert!(stdout.passes(&stdout));
193    /// assert!(!stdout.passes(&info));
194    /// ```
195    pub fn passes(&self, min: &LogLevelOrStdout) -> bool {
196        match (self, min) {
197            (LogLevelOrStdout::Stdout, LogLevelOrStdout::Stdout) => true,
198            (LogLevelOrStdout::Stdout, _) => false,
199            (LogLevelOrStdout::LogLevel(_), LogLevelOrStdout::Stdout) => true,
200            (LogLevelOrStdout::LogLevel(msg), LogLevelOrStdout::LogLevel(max)) => msg <= max,
201        }
202    }
203}
204
205impl From<LogLevel> for LogLevelOrStdout {
206    fn from(level: LogLevel) -> Self {
207        Self::LogLevel(level)
208    }
209}
210
211#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
212pub struct NodeError {
213    pub timestamp: uhlc::Timestamp,
214    pub cause: NodeErrorCause,
215    pub exit_status: NodeExitStatus,
216}
217
218impl std::fmt::Display for NodeError {
219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220        if let NodeErrorCause::FailedToSpawn(err) = &self.cause {
221            return write!(f, "failed to spawn node: {err}");
222        }
223        match &self.exit_status {
224            NodeExitStatus::Success => write!(f, "<success>"),
225            NodeExitStatus::IoError(err) => write!(f, "I/O error while reading exit status: {err}"),
226            NodeExitStatus::ExitCode(code) => write!(f, "exited with code {code}"),
227            NodeExitStatus::Signal(signal) => {
228                let signal_str: Cow<_> = match signal {
229                    1 => "SIGHUP".into(),
230                    2 => "SIGINT".into(),
231                    3 => "SIGQUIT".into(),
232                    4 => "SIGILL".into(),
233                    6 => "SIGABRT".into(),
234                    8 => "SIGFPE".into(),
235                    9 => "SIGKILL".into(),
236                    11 => "SIGSEGV".into(),
237                    13 => "SIGPIPE".into(),
238                    14 => "SIGALRM".into(),
239                    15 => "SIGTERM".into(),
240                    22 => "SIGTTOU".into(),
241                    23 => "SIGURG".into(),
242                    other => other.to_string().into(),
243                };
244                if matches!(self.cause, NodeErrorCause::GraceDuration) {
245                    write!(
246                        f,
247                        "node was killed by dora because it didn't react to a stop message in time ({signal_str})"
248                    )
249                } else {
250                    write!(f, "exited because of signal {signal_str}")
251                }
252            }
253            NodeExitStatus::Unknown => write!(f, "unknown exit status"),
254        }?;
255
256        match &self.cause {
257            NodeErrorCause::GraceDuration => {} // handled above
258            NodeErrorCause::Cascading { caused_by_node } => write!(
259                f,
260                ". This error occurred because node `{caused_by_node}` exited before connecting to dora."
261            )?,
262            // Rendered by the early return at the top of this function. Render
263            // it here too rather than `unreachable!()`: a `Display` impl must
264            // never panic (it runs implicitly on every log/`to_string()` of a
265            // `NodeError`, including on shutdown paths), and nothing structural
266            // ties this arm to that distant early return.
267            NodeErrorCause::FailedToSpawn(err) => write!(f, "failed to spawn node: {err}")?,
268            NodeErrorCause::Other { stderr } if stderr.is_empty() => {}
269            NodeErrorCause::Other { stderr } => {
270                let line: &str = "---------------------------------------------------------------------------------\n";
271                let stderr = stderr.trim_end();
272                write!(f, " with stderr output:\n{line}{stderr}\n{line}")?
273            }
274        }
275
276        Ok(())
277    }
278}
279
280#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
281pub enum NodeErrorCause {
282    /// Node was killed because it didn't react to a stop message in time.
283    GraceDuration,
284    /// Node failed because another node failed before,
285    Cascading {
286        caused_by_node: NodeId,
287    },
288    FailedToSpawn(String),
289    Other {
290        stderr: String,
291    },
292}
293
294/// How a node process ended.
295///
296/// Built from the node process's [`ExitStatus`](std::process::ExitStatus) (see
297/// the [`From`] impl), so it distinguishes a clean exit, a non-zero exit code,
298/// a killing signal (Unix), and the case where the daemon could not even wait
299/// on the process ([`IoError`](Self::IoError)).
300#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
301pub enum NodeExitStatus {
302    /// The process exited successfully (exit code 0).
303    Success,
304    /// The daemon failed to launch or wait on the process.
305    IoError(String),
306    /// The process exited with this non-zero code.
307    ExitCode(i32),
308    /// The process was terminated by this signal (Unix only).
309    Signal(i32),
310    /// The process ended in a way that is neither a code nor a signal.
311    Unknown,
312}
313
314impl NodeExitStatus {
315    /// Whether the node exited cleanly (i.e. this is [`Success`](Self::Success)).
316    ///
317    /// ```
318    /// use dora_message::common::NodeExitStatus;
319    ///
320    /// assert!(NodeExitStatus::Success.is_success());
321    /// assert!(!NodeExitStatus::ExitCode(1).is_success());
322    /// ```
323    pub fn is_success(&self) -> bool {
324        matches!(self, NodeExitStatus::Success)
325    }
326}
327
328impl From<Result<std::process::ExitStatus, std::io::Error>> for NodeExitStatus {
329    fn from(result: Result<std::process::ExitStatus, std::io::Error>) -> Self {
330        match result {
331            Ok(status) => {
332                if status.success() {
333                    NodeExitStatus::Success
334                } else if let Some(code) = status.code() {
335                    Self::ExitCode(code)
336                } else {
337                    #[cfg(unix)]
338                    {
339                        use std::os::unix::process::ExitStatusExt;
340                        if let Some(signal) = status.signal() {
341                            return Self::Signal(signal);
342                        }
343                    }
344                    Self::Unknown
345                }
346            }
347            Err(err) => Self::IoError(err.to_string()),
348        }
349    }
350}
351
352#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
353pub struct Timestamped<T> {
354    pub inner: T,
355    pub timestamp: uhlc::Timestamp,
356}
357
358impl Timestamped<InterDaemonEvent> {
359    /// Encode this event for the zenoh data plane and `dora record` files.
360    pub fn serialize(&self) -> eyre::Result<Vec<u8>> {
361        crate::encode_presized(self, self.inner.encode_size_hint())
362            .wrap_err("failed to serialize timestamped message")
363    }
364
365    pub fn deserialize_inter_daemon_event(bytes: &[u8]) -> eyre::Result<Self> {
366        crate::decode(bytes).wrap_err("failed to deserialize InterDaemonEvent")
367    }
368}
369
370pub type SharedMemoryId = String;
371
372#[derive(serde::Serialize, serde::Deserialize, Clone)]
373pub enum DataMessage {
374    Vec(#[serde(with = "crate::bulk_bytes")] AVec<u8, ConstAlign<128>>),
375}
376
377impl DataMessage {
378    /// Byte length of the carried payload.
379    pub fn len(&self) -> usize {
380        match self {
381            Self::Vec(v) => v.len(),
382        }
383    }
384
385    /// Whether the carried payload is empty (zero bytes).
386    pub fn is_empty(&self) -> bool {
387        self.len() == 0
388    }
389}
390
391impl fmt::Debug for DataMessage {
392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        match self {
394            Self::Vec(_) => f
395                .debug_struct("Vec")
396                .field("len", &self.len())
397                .finish_non_exhaustive(),
398        }
399    }
400}
401
402/// Identity of a running daemon: an optional operator-supplied machine id
403/// paired with a per-process time-ordered UUIDv7.
404///
405/// The machine id (typically a hostname) makes the [`Display`](std::fmt::Display)
406/// form human-readable and lets the coordinator route by machine, while the UUID
407/// keeps the id unique even when two daemons share a machine id (or none is set).
408/// The `Display` form is `"{machine_id}-{uuid}"`, or a bare `"{uuid}"` when there
409/// is no machine id; [`from_display_str`](Self::from_display_str) is its inverse.
410#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
411pub struct DaemonId {
412    machine_id: Option<String>,
413    uuid: Uuid,
414}
415
416impl DaemonId {
417    /// Create a fresh daemon id for the given machine, assigning a new
418    /// time-ordered UUIDv7. Pass `None` when no machine id is configured.
419    pub fn new(machine_id: Option<String>) -> Self {
420        DaemonId {
421            machine_id,
422            uuid: Uuid::now_v7(),
423        }
424    }
425
426    /// Whether this daemon was created with exactly the given machine id.
427    ///
428    /// Always `false` for a daemon created without a machine id.
429    pub fn matches_machine_id(&self, machine_id: &str) -> bool {
430        self.machine_id
431            .as_ref()
432            .map(|id| id == machine_id)
433            .unwrap_or_default()
434    }
435
436    /// The machine id this daemon was created with, or `None` if none was set.
437    pub fn machine_id(&self) -> Option<&str> {
438        self.machine_id.as_deref()
439    }
440
441    /// Reverse of [`Display`](std::fmt::Display): parse `"{machine_id}-{uuid}"`, or a bare
442    /// `"{uuid}"` when there is no machine id.
443    ///
444    /// Both the machine id (hostnames) and the canonical UUID contain `-`, so
445    /// splitting on a hyphen drops or corrupts a hyphenated machine id. Split
446    /// off the fixed-width 36-char canonical UUID suffix instead
447    /// (dora-rs/dora#2027).
448    ///
449    /// Expects exact `Display` output (no surrounding whitespace). The
450    /// machine-id path requires the canonical 36-char UUID suffix that
451    /// `Display` emits; the bare path accepts any form `Uuid::parse_str`
452    /// recognizes (canonical / simple / urn / braced).
453    ///
454    /// ```
455    /// use dora_message::common::DaemonId;
456    ///
457    /// // A hyphenated machine id round-trips through `Display` (dora-rs/dora#2027)...
458    /// let id = DaemonId::new(Some("my-host".to_string()));
459    /// assert_eq!(DaemonId::from_display_str(&id.to_string()), Some(id.clone()));
460    /// assert_eq!(id.machine_id(), Some("my-host"));
461    /// assert!(id.matches_machine_id("my-host"));
462    ///
463    /// // ...as does a daemon with no machine id (a bare UUID).
464    /// let anon = DaemonId::new(None);
465    /// assert_eq!(DaemonId::from_display_str(&anon.to_string()), Some(anon.clone()));
466    /// assert_eq!(anon.machine_id(), None);
467    ///
468    /// // Garbage does not parse to a bogus id.
469    /// assert_eq!(DaemonId::from_display_str("not-a-daemon-id"), None);
470    /// ```
471    pub fn from_display_str(s: &str) -> Option<Self> {
472        // No machine id: the whole string is the UUID.
473        if let Ok(uuid) = Uuid::parse_str(s) {
474            return Some(DaemonId {
475                machine_id: None,
476                uuid,
477            });
478        }
479        // `Display` writes the UUID via `{}` (canonical 36-char hyphenated
480        // form), preceded by `"{machine_id}-"`.
481        const UUID_LEN: usize = 36;
482        let split = s.len().checked_sub(UUID_LEN)?;
483        let uuid = Uuid::parse_str(s.get(split..)?).ok()?;
484        let machine_id = s.get(..split)?.strip_suffix('-')?;
485        Some(DaemonId {
486            machine_id: Some(machine_id.to_string()),
487            uuid,
488        })
489    }
490}
491
492impl std::fmt::Display for DaemonId {
493    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
494        if let Some(id) = &self.machine_id {
495            write!(f, "{id}-")?;
496        }
497        write!(f, "{}", self.uuid)
498    }
499}
500
501#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)]
502pub struct GitSource {
503    pub repo: String,
504    pub commit_hash: String,
505    /// Subdirectory of the repository the node lives in (monorepo support).
506    /// Build, env preparation, and spawn are rooted at `<clone>/<subdir>`.
507    #[serde(default, skip_serializing_if = "Option::is_none")]
508    pub subdir: Option<String>,
509    /// Hub provenance marker. Set when this git source was desugared from a
510    /// `hub:` reference — it tells the daemon to use confined path
511    /// resolution (no ambient `$PATH` fallback) for the node, and feeds the
512    /// lockfile and `dora hub` commands.
513    #[serde(default, skip_serializing_if = "Option::is_none")]
514    pub hub: Option<HubProvenance>,
515}
516
517/// Identity of the hub package a git source was resolved from.
518#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)]
519pub struct HubProvenance {
520    /// Index key (`namespace/name`).
521    pub name: String,
522    /// Resolved version.
523    pub version: String,
524    /// Digest of the index entry's manifest at lock time. The commit hash pins
525    /// the *source tree*, but the entrypoint, build command, and typed contract
526    /// (inputs/outputs/types) all live in the (mutable) index entry — so a
527    /// rewritten entry could change any of them for an already-pinned version.
528    /// `--locked` hard-errors if this digest no longer matches. `Option` for
529    /// back-compat with lockfiles written before this field existed.
530    #[serde(default, skip_serializing_if = "Option::is_none")]
531    pub manifest_digest: Option<String>,
532}
533
534/// Lockfile pin for a `hub:` node resolved to a prebuilt binary artifact
535/// (spec §8.2). Mirrors [`GitSource`] for the binary source form: the
536/// `url`+`sha256` pin the bytes (re-verified on download), and `hub` records
537/// the package/version/manifest provenance for `--locked` tamper detection.
538#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)]
539pub struct BinaryPin {
540    /// Platform the artifact was selected for at lock time (`<os>-<arch>`).
541    pub platform: String,
542    /// Download URL of the prebuilt artifact.
543    pub url: String,
544    /// SHA-256 the download must match.
545    pub sha256: String,
546    /// Hub provenance (index key, version, manifest digest).
547    pub hub: HubProvenance,
548}
549
550// Test roundtrip serialization of LogMessage
551#[cfg(test)]
552mod tests {
553    use super::*;
554
555    fn node_error_with_signal(signal: i32) -> NodeError {
556        NodeError {
557            timestamp: uhlc::HLC::default().new_timestamp(),
558            cause: NodeErrorCause::Other {
559                stderr: String::new(),
560            },
561            exit_status: NodeExitStatus::Signal(signal),
562        }
563    }
564
565    #[test]
566    fn node_error_signal_display_uses_linux_signal_names() {
567        for (signal, name) in [(6, "SIGABRT"), (22, "SIGTTOU"), (23, "SIGURG")] {
568            assert_eq!(
569                node_error_with_signal(signal).to_string(),
570                format!("exited because of signal {name}")
571            );
572        }
573    }
574
575    #[test]
576    fn node_error_signal_display_falls_back_to_signal_number() {
577        assert_eq!(
578            node_error_with_signal(40).to_string(),
579            "exited because of signal 40"
580        );
581    }
582
583    #[test]
584    fn test_log_message_serialization() {
585        let log_message = LogMessage {
586            build_id: Some(BuildId(Uuid::new_v4())),
587            dataflow_id: Some(DataflowId::from(Uuid::new_v4())),
588            node_id: Some(NodeId("node-1".to_string())),
589            daemon_id: Some(DaemonId::new(Some("machine-1".to_string()))),
590            level: LogLevelOrStdout::LogLevel(LogLevel::Info),
591            target: Some("target".to_string()),
592            module_path: Some("module::path".to_string()),
593            file: Some("file.rs".to_string()),
594            line: Some(42),
595            message: "This is a log message".to_string(),
596            timestamp: Utc::now(),
597            fields: Some(BTreeMap::from([("key".to_string(), "value".to_string())])),
598        };
599        let serialized = serde_yaml::to_string(&log_message).unwrap();
600        let deserialized: LogMessageHelper = serde_yaml::from_str(&serialized).unwrap();
601        assert_eq!(log_message, LogMessage::from(deserialized));
602    }
603
604    /// A `tracing` JSON line whose structured fields include numbers or bools
605    /// must still parse, keeping its level, instead of falling back to raw
606    /// `stdout` text that a level filter then drops.
607    #[test]
608    fn log_line_with_non_string_fields_keeps_its_level() {
609        let line = r#"{"timestamp":"2024-01-01T00:00:00Z","level":"INFO","fields":{"message":"got frame","frame":42,"ok":true,"ratio":0.5,"tag":null},"target":"node"}"#;
610        let helper: LogMessageHelper = serde_json::from_str(line).unwrap();
611        let message = LogMessage::from(helper);
612        assert_eq!(message.level, LogLevelOrStdout::LogLevel(LogLevel::Info));
613        assert_eq!(message.message, "got frame");
614        let fields = message.fields.unwrap();
615        assert_eq!(fields["frame"], "42");
616        assert_eq!(fields["ok"], "true");
617        assert_eq!(fields["ratio"], "0.5");
618        assert_eq!(fields["tag"], "null");
619    }
620
621    /// A line without a `fields` key still parses, with no fields.
622    #[test]
623    fn log_line_without_fields_parses() {
624        let line = r#"{"timestamp":"2024-01-01T00:00:00Z","level":"WARN","message":"m"}"#;
625        let helper: LogMessageHelper = serde_json::from_str(line).unwrap();
626        assert!(LogMessage::from(helper).fields.is_none());
627    }
628
629    #[test]
630    fn stdout_passes_stdout_filter() {
631        let stdout = LogLevelOrStdout::Stdout;
632        assert!(stdout.passes(&LogLevelOrStdout::Stdout));
633    }
634
635    /// A `node_id` recovered from the untrusted `fields` map must go through
636    /// `NodeId` validation. It was previously wrapped via the raw tuple
637    /// constructor (`.map(NodeId)`), bypassing `validate_node_id` and yielding
638    /// a `NodeId` that could contain `/` or dot-segments -- the very
639    /// path-traversal characters the newtype exists to forbid. Every other
640    /// field recovered here (`build_id`, `dataflow_id`, `daemon_id`) already
641    /// parses defensively; `node_id` was the odd one out.
642    #[test]
643    fn node_id_recovered_from_fields_is_validated() {
644        let make = |node_id: &str| LogMessageHelper {
645            build_id: None,
646            dataflow_id: None,
647            node_id: None,
648            daemon_id: None,
649            level: LogLevelOrStdout::Stdout,
650            target: None,
651            module_path: None,
652            file: None,
653            line: None,
654            message: Some("m".to_string()),
655            timestamp: Utc::now(),
656            fields: Some(BTreeMap::from([(
657                "node_id".to_string(),
658                node_id.to_string(),
659            )])),
660        };
661
662        // A valid id is promoted to the typed field.
663        assert_eq!(
664            LogMessage::from(make("sensor")).node_id,
665            Some("sensor".parse().unwrap())
666        );
667
668        // Invalid ids (path separator / dot-segment) are rejected rather than
669        // silently wrapped into an unvalidated NodeId.
670        assert_eq!(LogMessage::from(make("a/b")).node_id, None);
671        assert_eq!(LogMessage::from(make("../evil")).node_id, None);
672    }
673
674    /// A `build_id` back-filled from the `fields` map must survive a
675    /// `Display` round trip. `BuildId`'s `Display` wraps the UUID as
676    /// `BuildId(<uuid>)` -- the exact string emitted by the idiomatic
677    /// `tracing::info!(build_id = %build_id, ...)` (e.g. the coordinator's
678    /// build warnings). Recovery previously used `Uuid::parse_str`, which
679    /// rejects that wrapper and silently dropped the id; it now goes through
680    /// `BuildId::from_display_str`, matching how `daemon_id` is recovered.
681    #[test]
682    fn build_id_recovered_from_fields_survives_display_round_trip() {
683        let build_id = BuildId(Uuid::new_v4());
684        let make = |value: &str| LogMessageHelper {
685            build_id: None,
686            dataflow_id: None,
687            node_id: None,
688            daemon_id: None,
689            level: LogLevelOrStdout::Stdout,
690            target: None,
691            module_path: None,
692            file: None,
693            line: None,
694            message: Some("m".to_string()),
695            timestamp: Utc::now(),
696            fields: Some(BTreeMap::from([(
697                "build_id".to_string(),
698                value.to_string(),
699            )])),
700        };
701
702        // The `Display` form (`BuildId(<uuid>)`) is recovered...
703        assert_eq!(
704            LogMessage::from(make(&build_id.to_string())).build_id,
705            Some(build_id)
706        );
707        // ...and a bare UUID still works, for backward compatibility.
708        assert_eq!(
709            LogMessage::from(make(&build_id.uuid().to_string())).build_id,
710            Some(build_id)
711        );
712        // Garbage is rejected rather than wrapped into a bogus id.
713        assert_eq!(LogMessage::from(make("not-a-build-id")).build_id, None);
714    }
715
716    /// #2027: `DaemonId` must survive a `Display` -> `from_display_str` round
717    /// trip even when the machine id contains `-` (hostnames do). The old
718    /// `splitn(2, '-')` parse split on the first hyphen, which corrupted the
719    /// UUID (itself hyphenated) and silently dropped the daemon id.
720    #[test]
721    fn daemon_id_display_roundtrips_through_parse() {
722        let uuid = Uuid::new_v4();
723        for machine in [None, Some("host"), Some("my-host"), Some("a-b-c-d")] {
724            let id = DaemonId {
725                machine_id: machine.map(str::to_string),
726                uuid,
727            };
728            let parsed = DaemonId::from_display_str(&id.to_string())
729                .unwrap_or_else(|| panic!("failed to parse {id}"));
730            assert_eq!(parsed, id, "round-trip failed for machine_id={machine:?}");
731        }
732    }
733
734    /// A bare (machine-id-less) daemon id round-trips, and garbage does not
735    /// parse to a bogus id.
736    #[test]
737    fn daemon_id_parse_edge_cases() {
738        let uuid = Uuid::new_v4();
739        let bare = DaemonId {
740            machine_id: None,
741            uuid,
742        };
743        assert_eq!(DaemonId::from_display_str(&bare.to_string()), Some(bare));
744        assert_eq!(DaemonId::from_display_str("not-a-daemon-id"), None);
745        assert_eq!(DaemonId::from_display_str(""), None);
746    }
747
748    #[test]
749    fn stdout_fails_non_stdout_filters() {
750        let stdout = LogLevelOrStdout::Stdout;
751        assert!(!stdout.passes(&LogLevelOrStdout::LogLevel(LogLevel::Info)));
752        assert!(!stdout.passes(&LogLevelOrStdout::LogLevel(LogLevel::Warn)));
753        assert!(!stdout.passes(&LogLevelOrStdout::LogLevel(LogLevel::Error)));
754    }
755
756    #[test]
757    fn any_log_level_passes_stdout_filter() {
758        let stdout_filter = LogLevelOrStdout::Stdout;
759        for level in [
760            LogLevel::Error,
761            LogLevel::Warn,
762            LogLevel::Info,
763            LogLevel::Debug,
764            LogLevel::Trace,
765        ] {
766            assert!(
767                LogLevelOrStdout::LogLevel(level).passes(&stdout_filter),
768                "{level:?} should pass stdout filter"
769            );
770        }
771    }
772
773    #[test]
774    fn error_passes_less_verbose_filters() {
775        let error = LogLevelOrStdout::LogLevel(LogLevel::Error);
776        assert!(error.passes(&LogLevelOrStdout::LogLevel(LogLevel::Error)));
777        assert!(error.passes(&LogLevelOrStdout::LogLevel(LogLevel::Warn)));
778        assert!(error.passes(&LogLevelOrStdout::LogLevel(LogLevel::Info)));
779    }
780
781    #[test]
782    fn debug_fails_info_filter() {
783        let debug = LogLevelOrStdout::LogLevel(LogLevel::Debug);
784        assert!(!debug.passes(&LogLevelOrStdout::LogLevel(LogLevel::Info)));
785    }
786
787    #[test]
788    fn same_level_passes_itself() {
789        for level in [
790            LogLevel::Error,
791            LogLevel::Warn,
792            LogLevel::Info,
793            LogLevel::Debug,
794            LogLevel::Trace,
795        ] {
796            let l = LogLevelOrStdout::LogLevel(level);
797            assert!(l.passes(&l), "{level:?} should pass itself");
798        }
799    }
800
801    #[test]
802    fn trace_passes_trace_fails_debug() {
803        let trace = LogLevelOrStdout::LogLevel(LogLevel::Trace);
804        assert!(trace.passes(&LogLevelOrStdout::LogLevel(LogLevel::Trace)));
805        assert!(!trace.passes(&LogLevelOrStdout::LogLevel(LogLevel::Debug)));
806    }
807
808    #[test]
809    fn daemon_id_uses_v7_uuid() {
810        let id = DaemonId::new(None);
811        // v7 UUIDs have version nibble = 7
812        assert_eq!(id.uuid.get_version_num(), 7);
813    }
814}