Skip to main content

cu29_export/
lib.rs

1//! Log export helpers for Copper applications.
2//!
3//! This crate serves two related use cases:
4//!
5//! - Rust logreader binaries built with [`run_cli`]
6//! - optional Python-facing iterators for offline analysis of structured logs,
7//!   runtime lifecycle records, and app-specific CopperLists
8//!
9//! Python support here is intentionally offline. It reads data that Copper has
10//! already recorded. That is very different from putting Python on the runtime
11//! execution path, and it does not compromise realtime behavior during robot
12//! execution.
13//!
14//! For runtime Python task prototyping, see `cu-python-task` instead.
15
16mod fsck;
17pub mod logstats;
18
19#[cfg(feature = "mcap")]
20pub mod mcap_export;
21
22#[cfg(feature = "mcap")]
23pub mod serde_to_jsonschema;
24
25use bincode::Decode;
26use bincode::config::standard;
27use bincode::decode_from_std_read;
28use bincode::error::DecodeError;
29use clap::{Parser, Subcommand, ValueEnum};
30use cu29::UnifiedLogType;
31use cu29::prelude::*;
32use cu29_intern_strs::read_interned_strings;
33use fsck::check;
34#[cfg(feature = "mcap")]
35use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
36use logstats::{compute_logstats, write_logstats};
37use serde::Serialize;
38use std::fmt::{Display, Formatter};
39#[cfg(feature = "mcap")]
40use std::io::IsTerminal;
41use std::io::Read;
42use std::path::{Path, PathBuf};
43
44#[cfg(feature = "mcap")]
45pub use mcap_export::{McapExportStats, export_to_mcap, export_to_mcap_with_schemas, mcap_info};
46
47#[cfg(feature = "mcap")]
48#[allow(deprecated)]
49pub use cu29::prelude::PayloadSchemas;
50
51#[cfg(feature = "mcap")]
52pub use serde_to_jsonschema::trace_type_to_jsonschema;
53
54/// Registers the typed CopperList decoder used by the generic Python iterator.
55///
56/// Applications normally call this indirectly through
57/// [`copperlist_iterator_unified_typed_py`].
58#[cfg(feature = "python")]
59pub use python::register_copperlist_python_type;
60
61/// Creates a Python CopperList iterator for a specific CopperList tuple type.
62///
63/// This is intended for app-specific Python modules that know their generated
64/// CopperList type at compile time. The helper registers the decoder and returns
65/// an iterator object that yields Python objects built from the recorded
66/// CopperLists.
67#[cfg(feature = "python")]
68pub fn copperlist_iterator_unified_typed_py<P>(
69    unified_src_path: &str,
70    py: pyo3::Python<'_>,
71) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>>
72where
73    P: CopperListTuple + 'static,
74{
75    let _ = cu29::logcodec::seed_effective_config_from_log::<P>(Path::new(unified_src_path))
76        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
77    register_copperlist_python_type::<P>()
78        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
79    let iter = python::copperlist_iterator_unified(unified_src_path)?;
80    pyo3::Py::new(py, iter).map(|obj| obj.into())
81}
82
83/// Creates a Python `RuntimeLifecycleRecord` iterator from a unified log.
84///
85/// This is useful for offline analysis scripts that need to inspect mission
86/// starts, stops, faults, and related runtime events.
87#[cfg(feature = "python")]
88pub fn runtime_lifecycle_iterator_unified_py(
89    unified_src_path: &str,
90    py: pyo3::Python<'_>,
91) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
92    let iter = python::runtime_lifecycle_iterator_unified(unified_src_path)?;
93    pyo3::Py::new(py, iter).map(|obj| obj.into())
94}
95#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
96pub enum ExportFormat {
97    Json,
98    Csv,
99}
100
101impl Display for ExportFormat {
102    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
103        match self {
104            ExportFormat::Json => write!(f, "json"),
105            ExportFormat::Csv => write!(f, "csv"),
106        }
107    }
108}
109
110/// This is a generator for a main function to build a log extractor.
111#[derive(Parser)]
112#[command(author, version, about)]
113pub struct LogReaderCli {
114    /// The base path is the name with no _0 _1 et the end.
115    /// for example for toto_0.copper, toto_1.copper ... the base name is toto.copper
116    pub unifiedlog_base: PathBuf,
117
118    #[command(subcommand)]
119    pub command: Command,
120}
121
122#[derive(Subcommand)]
123pub enum Command {
124    /// Extract logs
125    ExtractTextLog { log_index: PathBuf },
126    /// Extract copperlists
127    ExtractCopperlists {
128        #[arg(short, long, default_value_t = ExportFormat::Json)]
129        export_format: ExportFormat,
130    },
131    /// Check the log and dump info about it.
132    Fsck {
133        #[arg(short, long, action = clap::ArgAction::Count)]
134        verbose: u8,
135        /// Decode and print RuntimeLifecycle events.
136        #[arg(long)]
137        dump_runtime_lifecycle: bool,
138    },
139    /// Export log statistics to JSON for offline DAG rendering.
140    LogStats {
141        /// Output JSON file path
142        #[arg(short, long, default_value = "cu29_logstats.json")]
143        output: PathBuf,
144        /// Config file used to map outputs to edges
145        #[arg(long, default_value = "copperconfig.ron")]
146        config: PathBuf,
147        /// Mission id override; defaults to the mission recorded in the log
148        #[arg(long)]
149        mission: Option<String>,
150        /// Comma-separated Cargo features used by conditional config fragments
151        #[arg(long, value_delimiter = ',')]
152        features: Vec<String>,
153    },
154    /// Export copperlists to MCAP format (requires 'mcap' feature)
155    #[cfg(feature = "mcap")]
156    ExportMcap {
157        /// Output MCAP file path
158        #[arg(short, long)]
159        output: PathBuf,
160        /// Force progress bar even when stderr is not a TTY
161        #[arg(long)]
162        progress: bool,
163        /// Suppress the progress bar
164        #[arg(long)]
165        quiet: bool,
166    },
167    /// Inspect an MCAP file and dump metadata, schemas, and stats (requires 'mcap' feature)
168    #[cfg(feature = "mcap")]
169    McapInfo {
170        /// Path to the MCAP file to inspect
171        mcap_file: PathBuf,
172        /// Show full schema content
173        #[arg(short, long)]
174        schemas: bool,
175        /// Show sample messages (first N messages per channel)
176        #[arg(short = 'n', long, default_value_t = 0)]
177        sample_messages: usize,
178    },
179}
180
181fn write_json_pretty<T: Serialize + ?Sized>(value: &T) -> CuResult<()> {
182    serde_json::to_writer_pretty(std::io::stdout(), value)
183        .map_err(|e| CuError::new_with_cause("Failed to write JSON output", e))
184}
185
186fn write_json<T: Serialize + ?Sized>(value: &T) -> CuResult<()> {
187    serde_json::to_writer(std::io::stdout(), value)
188        .map_err(|e| CuError::new_with_cause("Failed to write JSON output", e))
189}
190
191fn build_read_logger(unifiedlog_base: &Path) -> CuResult<UnifiedLoggerRead> {
192    let logger = UnifiedLoggerBuilder::new()
193        .file_base_name(unifiedlog_base)
194        .build()
195        .map_err(|e| CuError::new_with_cause("Failed to create logger", e))?;
196    match logger {
197        UnifiedLogger::Read(dl) => Ok(dl),
198        UnifiedLogger::Write(_) => Err(CuError::from(
199            "Expected read-only unified logger in export CLI",
200        )),
201    }
202}
203
204/// This is a generator for a main function to build a log extractor.
205/// It depends on the specific type of the CopperList payload that is determined at compile time from the configuration.
206///
207#[cfg(feature = "mcap")]
208pub fn run_cli<P>() -> CuResult<()>
209where
210    P: CopperListTuple + CuPayloadRawBytes + 'static,
211{
212    #[cfg(feature = "python")]
213    let _ = python::register_copperlist_python_type::<P>();
214
215    run_cli_inner::<P>()
216}
217
218/// This is a generator for a main function to build a log extractor.
219/// It depends on the specific type of the CopperList payload that is determined at compile time from the configuration.
220#[cfg(not(feature = "mcap"))]
221pub fn run_cli<P>() -> CuResult<()>
222where
223    P: CopperListTuple + CuPayloadRawBytes + 'static,
224{
225    #[cfg(feature = "python")]
226    let _ = python::register_copperlist_python_type::<P>();
227
228    run_cli_inner::<P>()
229}
230
231#[cfg(feature = "mcap")]
232fn run_cli_inner<P>() -> CuResult<()>
233where
234    P: CopperListTuple + CuPayloadRawBytes + 'static,
235{
236    let args = LogReaderCli::parse();
237    let unifiedlog_base = args.unifiedlog_base;
238    let _ = cu29::logcodec::seed_effective_config_from_log::<P>(&unifiedlog_base)?;
239
240    let mut dl = build_read_logger(&unifiedlog_base)?;
241
242    match args.command {
243        Command::ExtractTextLog { log_index } => {
244            let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::StructuredLogLine);
245            textlog_dump(reader, &log_index)?;
246        }
247        Command::ExtractCopperlists { export_format } => {
248            println!("Extracting copperlists with format: {export_format}");
249            let mut reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::CopperList);
250            let iter = copperlists_reader::<P>(&mut reader);
251
252            match export_format {
253                ExportFormat::Json => {
254                    for entry in iter {
255                        write_json_pretty(&entry)?;
256                    }
257                }
258                ExportFormat::Csv => {
259                    let mut first = true;
260                    for origin in P::get_all_task_ids() {
261                        if !first {
262                            print!(", ");
263                        } else {
264                            print!("id, ");
265                        }
266                        print!("{origin}_time, {origin}_tov, {origin},");
267                        first = false;
268                    }
269                    println!();
270                    for entry in iter {
271                        let mut first = true;
272                        for msg in entry.cumsgs() {
273                            if let Some(payload) = msg.payload() {
274                                if !first {
275                                    print!(", ");
276                                } else {
277                                    print!("{}, ", entry.id);
278                                }
279                                let metadata = msg.metadata();
280                                print!("{}, {}, ", metadata.process_time(), msg.tov());
281                                write_json(payload)?; // TODO: escape for CSV
282                                first = false;
283                            }
284                        }
285                        println!();
286                    }
287                }
288            }
289        }
290        Command::Fsck {
291            verbose,
292            dump_runtime_lifecycle,
293        } => {
294            if let Some(value) = check::<P>(&mut dl, verbose, dump_runtime_lifecycle) {
295                return value;
296            }
297        }
298        Command::LogStats {
299            output,
300            config,
301            mission,
302            features,
303        } => {
304            run_logstats::<P>(&unifiedlog_base, dl, output, config, mission, &features)?;
305        }
306        #[cfg(feature = "mcap")]
307        Command::ExportMcap {
308            output,
309            progress,
310            quiet,
311        } => {
312            println!("Exporting copperlists to MCAP format: {}", output.display());
313
314            let show_progress = should_show_progress(progress, quiet);
315            let total_bytes = if show_progress {
316                Some(copperlist_total_bytes(&unifiedlog_base)?)
317            } else {
318                None
319            };
320
321            let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::CopperList);
322
323            // Export to MCAP with schemas derived from generated output metadata.
324            let stats = if let Some(total_bytes) = total_bytes {
325                let progress_bar = make_progress_bar(total_bytes);
326                let reader = ProgressReader::new(reader, progress_bar.clone());
327                let result = export_to_mcap_impl::<P>(reader, &output);
328                progress_bar.finish_and_clear();
329                result?
330            } else {
331                export_to_mcap_impl::<P>(reader, &output)?
332            };
333            println!("{stats}");
334        }
335        #[cfg(feature = "mcap")]
336        Command::McapInfo {
337            mcap_file,
338            schemas,
339            sample_messages,
340        } => {
341            mcap_info(&mcap_file, schemas, sample_messages)?;
342        }
343    }
344
345    Ok(())
346}
347
348#[cfg(not(feature = "mcap"))]
349fn run_cli_inner<P>() -> CuResult<()>
350where
351    P: CopperListTuple + CuPayloadRawBytes + 'static,
352{
353    let args = LogReaderCli::parse();
354    let unifiedlog_base = args.unifiedlog_base;
355    let _ = cu29::logcodec::seed_effective_config_from_log::<P>(&unifiedlog_base)?;
356
357    let mut dl = build_read_logger(&unifiedlog_base)?;
358
359    match args.command {
360        Command::ExtractTextLog { log_index } => {
361            let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::StructuredLogLine);
362            textlog_dump(reader, &log_index)?;
363        }
364        Command::ExtractCopperlists { export_format } => {
365            println!("Extracting copperlists with format: {export_format}");
366            let mut reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::CopperList);
367            let iter = copperlists_reader::<P>(&mut reader);
368
369            match export_format {
370                ExportFormat::Json => {
371                    for entry in iter {
372                        write_json_pretty(&entry)?;
373                    }
374                }
375                ExportFormat::Csv => {
376                    let mut first = true;
377                    for origin in P::get_all_task_ids() {
378                        if !first {
379                            print!(", ");
380                        } else {
381                            print!("id, ");
382                        }
383                        print!("{origin}_time, {origin}_tov, {origin},");
384                        first = false;
385                    }
386                    println!();
387                    for entry in iter {
388                        let mut first = true;
389                        for msg in entry.cumsgs() {
390                            if let Some(payload) = msg.payload() {
391                                if !first {
392                                    print!(", ");
393                                } else {
394                                    print!("{}, ", entry.id);
395                                }
396                                let metadata = msg.metadata();
397                                print!("{}, {}, ", metadata.process_time(), msg.tov());
398                                write_json(payload)?;
399                                first = false;
400                            }
401                        }
402                        println!();
403                    }
404                }
405            }
406        }
407        Command::Fsck {
408            verbose,
409            dump_runtime_lifecycle,
410        } => {
411            if let Some(value) = check::<P>(&mut dl, verbose, dump_runtime_lifecycle) {
412                return value;
413            }
414        }
415        Command::LogStats {
416            output,
417            config,
418            mission,
419            features,
420        } => {
421            run_logstats::<P>(&unifiedlog_base, dl, output, config, mission, &features)?;
422        }
423    }
424
425    Ok(())
426}
427
428fn run_logstats<P>(
429    unifiedlog_base: &Path,
430    dl: UnifiedLoggerRead,
431    output: PathBuf,
432    config: PathBuf,
433    mission: Option<String>,
434    features: &[String],
435) -> CuResult<()>
436where
437    P: CopperListTuple + CuPayloadRawBytes,
438{
439    let config_path = config
440        .to_str()
441        .ok_or_else(|| CuError::from("Config path is not valid UTF-8"))?;
442    let feature_refs = features.iter().map(String::as_str).collect::<Vec<_>>();
443    let cfg = cu29::config::read_configuration_with_features(config_path, &feature_refs)
444        .map_err(|e| CuError::new_with_cause("Failed to read configuration", e))?;
445    let logged_mission =
446        if mission.is_none() && matches!(&cfg.graphs, cu29::config::ConfigGraphs::Missions(_)) {
447            unified_log_mission(unifiedlog_base)?
448        } else {
449            None
450        };
451    let mission = resolve_logstats_mission(&cfg, mission, logged_mission);
452    let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::CopperList);
453    let stats = compute_logstats::<P>(reader, &cfg, mission.as_deref())?;
454    write_logstats(&stats, &output)
455}
456
457fn resolve_logstats_mission(
458    config: &CuConfig,
459    requested: Option<String>,
460    logged: Option<String>,
461) -> Option<String> {
462    if requested.is_some() {
463        return requested;
464    }
465    let cu29::config::ConfigGraphs::Missions(graphs) = &config.graphs else {
466        return None;
467    };
468    if let Some(logged) = logged
469        && graphs.contains_key(&logged)
470    {
471        return Some(logged);
472    }
473    if graphs.contains_key("default") {
474        return Some("default".to_string());
475    }
476    graphs.keys().min().cloned()
477}
478
479/// Helper function for MCAP export.
480///
481/// Uses generated per-slot payload type metadata to derive schemas.
482#[cfg(feature = "mcap")]
483fn export_to_mcap_impl<P>(src: impl Read, output: &Path) -> CuResult<McapExportStats>
484where
485    P: CopperListTuple,
486{
487    mcap_export::export_to_mcap::<P, _>(src, output)
488}
489
490#[cfg(feature = "mcap")]
491struct ProgressReader<R> {
492    inner: R,
493    progress: ProgressBar,
494}
495
496#[cfg(feature = "mcap")]
497impl<R> ProgressReader<R> {
498    fn new(inner: R, progress: ProgressBar) -> Self {
499        Self { inner, progress }
500    }
501}
502
503#[cfg(feature = "mcap")]
504impl<R: Read> Read for ProgressReader<R> {
505    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
506        let read = self.inner.read(buf)?;
507        if read > 0 {
508            self.progress.inc(read as u64);
509        }
510        Ok(read)
511    }
512}
513
514#[cfg(feature = "mcap")]
515fn make_progress_bar(total_bytes: u64) -> ProgressBar {
516    let progress_bar = ProgressBar::new(total_bytes);
517    progress_bar.set_draw_target(ProgressDrawTarget::stderr_with_hz(5));
518
519    let style = ProgressStyle::with_template(
520        "[{elapsed_precise}] {bar:40} {bytes}/{total_bytes} ({bytes_per_sec}, ETA {eta})",
521    )
522    .unwrap_or_else(|_| ProgressStyle::default_bar());
523
524    progress_bar.set_style(style.progress_chars("=>-"));
525    progress_bar
526}
527
528#[cfg(feature = "mcap")]
529fn should_show_progress(force_progress: bool, quiet: bool) -> bool {
530    !quiet && (force_progress || std::io::stderr().is_terminal())
531}
532
533#[cfg(feature = "mcap")]
534fn copperlist_total_bytes(log_base: &Path) -> CuResult<u64> {
535    let mut reader = UnifiedLoggerRead::new(log_base)
536        .map_err(|e| CuError::new_with_cause("Failed to open log for progress estimation", e))?;
537    reader
538        .scan_section_bytes(UnifiedLogType::CopperList)
539        .map_err(|e| CuError::new_with_cause("Failed to scan log for progress estimation", e))
540}
541
542fn read_next_entry<T: Decode<()>>(src: &mut impl Read) -> Option<T> {
543    let entry = decode_from_std_read::<T, _, _>(src, standard());
544    match entry {
545        Ok(entry) => Some(entry),
546        Err(DecodeError::UnexpectedEnd { .. }) => None,
547        Err(DecodeError::Io { inner, additional }) => {
548            if inner.kind() == std::io::ErrorKind::UnexpectedEof {
549                None
550            } else {
551                println!("Error {inner:?} additional:{additional}");
552                None
553            }
554        }
555        Err(e) => {
556            println!("Error {e:?}");
557            None
558        }
559    }
560}
561
562/// Reads received archive provenance, inclusive source gaps and verified recovery points.
563pub fn stream_continuity_reader(
564    mut src: impl Read,
565) -> impl Iterator<Item = cu29::continuity::StreamContinuityRecord> {
566    std::iter::from_fn(move || read_next_entry(&mut src))
567}
568
569/// Extracts the copper lists from a binary representation.
570/// P is the Payload determined by the configuration of the application.
571pub fn copperlists_reader<P: CopperListTuple>(
572    mut src: impl Read,
573) -> impl Iterator<Item = CopperList<P>> {
574    std::iter::from_fn(move || read_next_entry::<CopperList<P>>(&mut src))
575}
576
577/// Extracts the keyframes from the log.
578pub fn keyframes_reader(mut src: impl Read) -> impl Iterator<Item = KeyFrame> {
579    std::iter::from_fn(move || read_next_entry::<KeyFrame>(&mut src))
580}
581
582/// Extracts the runtime lifecycle records from the log.
583pub fn runtime_lifecycle_reader(
584    mut src: impl Read,
585) -> impl Iterator<Item = RuntimeLifecycleRecord> {
586    std::iter::from_fn(move || read_next_entry::<RuntimeLifecycleRecord>(&mut src))
587}
588
589/// Returns the first mission announced by the runtime lifecycle section, if any.
590pub fn unified_log_mission(unifiedlog_base: &Path) -> CuResult<Option<String>> {
591    let dl = build_read_logger(unifiedlog_base)?;
592    let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::RuntimeLifecycle);
593    Ok(
594        runtime_lifecycle_reader(reader).find_map(|entry| match entry.event {
595            RuntimeLifecycleEvent::MissionStarted { mission } => Some(mission),
596            _ => None,
597        }),
598    )
599}
600
601/// Ensures the unified log was recorded for the expected mission.
602pub fn assert_unified_log_mission(unifiedlog_base: &Path, expected_mission: &str) -> CuResult<()> {
603    match unified_log_mission(unifiedlog_base)? {
604        Some(actual_mission) if actual_mission == expected_mission => Ok(()),
605        Some(actual_mission) => Err(CuError::from(format!(
606            "Mission mismatch: expected '{expected_mission}', found '{actual_mission}'"
607        ))),
608        None => Err(CuError::from(format!(
609            "No MissionStarted runtime lifecycle event found while validating expected mission '{expected_mission}'"
610        ))),
611    }
612}
613
614pub fn structlog_reader(mut src: impl Read) -> impl Iterator<Item = CuResult<CuLogEntry>> {
615    std::iter::from_fn(move || {
616        let entry = decode_from_std_read::<CuLogEntry, _, _>(&mut src, standard());
617
618        match entry {
619            Err(DecodeError::UnexpectedEnd { .. }) => None,
620            Err(DecodeError::Io {
621                inner,
622                additional: _,
623            }) => {
624                if inner.kind() == std::io::ErrorKind::UnexpectedEof {
625                    None
626                } else {
627                    Some(Err(CuError::new_with_cause("Error reading log", inner)))
628                }
629            }
630            Err(e) => Some(Err(CuError::new_with_cause("Error reading log", e))),
631            Ok(entry) => {
632                if entry.msg_index == 0 {
633                    None
634                } else {
635                    Some(Ok(entry))
636                }
637            }
638        }
639    })
640}
641
642/// Full dump of the copper structured log from its binary representation.
643/// This rebuilds a textual log.
644/// src: the source of the log data
645/// index: the path to the index file (containing the interned strings constructed at build time)
646pub fn textlog_dump(src: impl Read, index: &Path) -> CuResult<()> {
647    let all_strings = read_interned_strings(index).map_err(|e| {
648        CuError::new_with_cause(
649            "Failed to read interned strings from index",
650            std::io::Error::other(e),
651        )
652    })?;
653
654    for result in structlog_reader(src) {
655        let entry = result?;
656        match rebuild_logline(&all_strings, &entry) {
657            Ok(line) => println!("{line}"),
658            Err(e) => println!("Failed to rebuild log line: {e:?}"),
659        }
660    }
661
662    Ok(())
663}
664
665// Only compiled for users opting into the Python interface.
666#[cfg(feature = "python")]
667mod python {
668    use bincode::config::standard;
669    use bincode::decode_from_std_read;
670    use bincode::error::DecodeError;
671    use cu29::bevy_reflect::{PartialReflect, ReflectRef, VariantType};
672    use cu29::prelude::*;
673    use cu29_intern_strs::read_interned_strings;
674    use pyo3::exceptions::{PyIOError, PyRuntimeError};
675    use pyo3::prelude::*;
676    use pyo3::types::{PyDelta, PyDict, PyList};
677    use std::io::Read;
678    use std::path::Path;
679    use std::sync::OnceLock;
680
681    type CopperListDecodeFn =
682        for<'py> fn(&mut Box<dyn Read + Send + Sync>, Python<'py>) -> Option<PyResult<Py<PyAny>>>;
683    static COPPERLIST_DECODER: OnceLock<CopperListDecodeFn> = OnceLock::new();
684
685    /// Iterator over structured Copper log entries.
686    #[pyclass]
687    pub struct PyLogIterator {
688        reader: Box<dyn Read + Send + Sync>,
689    }
690
691    /// Iterator over application-specific CopperLists decoded into Python values.
692    #[pyclass]
693    pub struct PyCopperListIterator {
694        reader: Box<dyn Read + Send + Sync>,
695        decode_next: CopperListDecodeFn,
696    }
697
698    /// Iterator over runtime lifecycle records stored in a unified log.
699    #[pyclass]
700    pub struct PyRuntimeLifecycleIterator {
701        reader: Box<dyn Read + Send + Sync>,
702    }
703
704    /// Helper wrapper used when reflected unit-bearing values are exposed to Python.
705    #[pyclass(get_all)]
706    pub struct PyUnitValue {
707        pub value: f64,
708        pub unit: String,
709    }
710
711    /// Register the Python decoder for one concrete CopperList tuple type.
712    ///
713    /// App-specific extension modules call this once before constructing a
714    /// `PyCopperListIterator`.
715    pub fn register_copperlist_python_type<P>() -> CuResult<()>
716    where
717        P: CopperListTuple,
718    {
719        if COPPERLIST_DECODER.get().is_none() {
720            COPPERLIST_DECODER
721                .set(decode_next_copperlist::<P>)
722                .map_err(|_| CuError::from("Failed to register CopperList Python decoder"))?;
723        }
724        Ok(())
725    }
726    #[pymethods]
727    impl PyLogIterator {
728        fn __iter__(slf: PyRefMut<Self>) -> PyRefMut<Self> {
729            slf
730        }
731
732        fn __next__(mut slf: PyRefMut<Self>) -> Option<PyResult<PyCuLogEntry>> {
733            match decode_from_std_read::<CuLogEntry, _, _>(&mut slf.reader, standard()) {
734                Ok(entry) => {
735                    if entry.msg_index == 0 {
736                        None
737                    } else {
738                        Some(Ok(PyCuLogEntry { inner: entry }))
739                    }
740                }
741                Err(DecodeError::UnexpectedEnd { .. }) => None,
742                Err(DecodeError::Io { inner, .. })
743                    if inner.kind() == std::io::ErrorKind::UnexpectedEof =>
744                {
745                    None
746                }
747                Err(e) => Some(Err(PyIOError::new_err(e.to_string()))),
748            }
749        }
750    }
751
752    #[pymethods]
753    impl PyCopperListIterator {
754        fn __iter__(slf: PyRefMut<Self>) -> PyRefMut<Self> {
755            slf
756        }
757
758        fn __next__(mut slf: PyRefMut<Self>, py: Python<'_>) -> Option<PyResult<Py<PyAny>>> {
759            (slf.decode_next)(&mut slf.reader, py)
760        }
761    }
762
763    #[pymethods]
764    impl PyRuntimeLifecycleIterator {
765        fn __iter__(slf: PyRefMut<Self>) -> PyRefMut<Self> {
766            slf
767        }
768
769        fn __next__(mut slf: PyRefMut<Self>, py: Python<'_>) -> Option<PyResult<Py<PyAny>>> {
770            let entry = super::read_next_entry::<RuntimeLifecycleRecord>(&mut slf.reader)?;
771            Some(runtime_lifecycle_record_to_py(&entry, py))
772        }
773    }
774    /// Create an iterator over structured log entries from a bare structured log file.
775    ///
776    /// This is the non-unified-log path used by standalone structured log setups.
777    /// The function returns the iterator together with the interned string table
778    /// needed to format each message.
779    #[pyfunction]
780    pub fn struct_log_iterator_bare(
781        bare_struct_src_path: &str,
782        index_path: &str,
783    ) -> PyResult<(PyLogIterator, Vec<String>)> {
784        let file = std::fs::File::open(bare_struct_src_path)
785            .map_err(|e| PyIOError::new_err(e.to_string()))?;
786        let all_strings = read_interned_strings(Path::new(index_path))
787            .map_err(|e| PyIOError::new_err(e.to_string()))?;
788        Ok((
789            PyLogIterator {
790                reader: Box::new(file),
791            },
792            all_strings,
793        ))
794    }
795    /// Create an iterator over structured log entries from a unified log file.
796    ///
797    /// The function returns the iterator together with the interned string table
798    /// needed to rebuild the text messages.
799    #[pyfunction]
800    pub fn struct_log_iterator_unified(
801        unified_src_path: &str,
802        index_path: &str,
803    ) -> PyResult<(PyLogIterator, Vec<String>)> {
804        let all_strings = read_interned_strings(Path::new(index_path))
805            .map_err(|e| PyIOError::new_err(e.to_string()))?;
806
807        let logger = UnifiedLoggerBuilder::new()
808            .file_base_name(Path::new(unified_src_path))
809            .build()
810            .map_err(|e| PyIOError::new_err(e.to_string()))?;
811        let dl = match logger {
812            UnifiedLogger::Read(dl) => dl,
813            UnifiedLogger::Write(_) => {
814                return Err(PyIOError::new_err(
815                    "Expected read-only unified logger for Python export",
816                ));
817            }
818        };
819
820        let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::StructuredLogLine);
821        Ok((
822            PyLogIterator {
823                reader: Box::new(reader),
824            },
825            all_strings,
826        ))
827    }
828
829    /// Create an iterator over CopperLists from a unified log file.
830    ///
831    /// The concrete CopperList tuple type must be registered from Rust first with
832    /// `register_copperlist_python_type::<P>()`.
833    #[pyfunction]
834    pub fn copperlist_iterator_unified(unified_src_path: &str) -> PyResult<PyCopperListIterator> {
835        let decode_next = *COPPERLIST_DECODER.get().ok_or_else(|| {
836            PyRuntimeError::new_err(
837                "CopperList decoder is not registered. \
838Call register_copperlist_python_type::<P>() from Rust before using this function.",
839            )
840        })?;
841
842        let logger = UnifiedLoggerBuilder::new()
843            .file_base_name(Path::new(unified_src_path))
844            .build()
845            .map_err(|e| PyIOError::new_err(e.to_string()))?;
846        let dl = match logger {
847            UnifiedLogger::Read(dl) => dl,
848            UnifiedLogger::Write(_) => {
849                return Err(PyIOError::new_err(
850                    "Expected read-only unified logger for Python export",
851                ));
852            }
853        };
854
855        let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::CopperList);
856        Ok(PyCopperListIterator {
857            reader: Box::new(reader),
858            decode_next,
859        })
860    }
861
862    /// Create an iterator over runtime lifecycle records from a unified log file.
863    #[pyfunction]
864    pub fn runtime_lifecycle_iterator_unified(
865        unified_src_path: &str,
866    ) -> PyResult<PyRuntimeLifecycleIterator> {
867        let logger = UnifiedLoggerBuilder::new()
868            .file_base_name(Path::new(unified_src_path))
869            .build()
870            .map_err(|e| PyIOError::new_err(e.to_string()))?;
871        let dl = match logger {
872            UnifiedLogger::Read(dl) => dl,
873            UnifiedLogger::Write(_) => {
874                return Err(PyIOError::new_err(
875                    "Expected read-only unified logger for Python export",
876                ));
877            }
878        };
879
880        let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::RuntimeLifecycle);
881        Ok(PyRuntimeLifecycleIterator {
882            reader: Box::new(reader),
883        })
884    }
885    /// Python wrapper for [`CuLogEntry`].
886    #[pyclass]
887    pub struct PyCuLogEntry {
888        pub inner: CuLogEntry,
889    }
890
891    #[pymethods]
892    impl PyCuLogEntry {
893        /// Return the timestamp of the log entry as a `datetime.timedelta`.
894        pub fn ts<'a>(&self, py: Python<'a>) -> PyResult<Bound<'a, PyDelta>> {
895            let nanoseconds: u64 = self.inner.time.into();
896
897            // Convert nanoseconds to seconds and microseconds
898            let days = (nanoseconds / 86_400_000_000_000) as i32;
899            let seconds = (nanoseconds / 1_000_000_000) as i32;
900            let microseconds = ((nanoseconds % 1_000_000_000) / 1_000) as i32;
901
902            PyDelta::new(py, days, seconds, microseconds, false)
903        }
904
905        /// Return the index of the message format string in the interned string table.
906        pub fn msg_index(&self) -> u32 {
907            self.inner.msg_index
908        }
909
910        /// Return the CopperList id captured for this log entry, if any.
911        pub fn culistid(&self) -> Option<u64> {
912            self.inner.origin.culistid
913        }
914
915        /// Return the runtime component id captured for this log entry, if any.
916        pub fn component_id(&self) -> Option<u32> {
917            self.inner.origin.component_id
918        }
919
920        /// Return the task index captured for this log entry, if any.
921        pub fn task_index(&self) -> Option<u32> {
922            self.inner.origin.task_index
923        }
924
925        /// Return the indexes of the parameter names in the interned string table.
926        pub fn paramname_indexes(&self) -> Vec<u32> {
927            self.inner.paramname_indexes.iter().copied().collect()
928        }
929
930        /// Return the structured parameters carried by this log line.
931        pub fn params(&self, py: Python<'_>) -> PyResult<Vec<Py<PyAny>>> {
932            self.inner
933                .params
934                .iter()
935                .map(|value| value_to_py(value, py))
936                .collect()
937        }
938    }
939
940    /// This needs to match the name of the generated '.so'
941    #[pymodule(name = "libcu29_export")]
942    fn cu29_export(m: &Bound<'_, PyModule>) -> PyResult<()> {
943        m.add_class::<PyCuLogEntry>()?;
944        m.add_class::<PyLogIterator>()?;
945        m.add_class::<PyCopperListIterator>()?;
946        m.add_class::<PyRuntimeLifecycleIterator>()?;
947        m.add_class::<PyUnitValue>()?;
948        m.add_function(wrap_pyfunction!(struct_log_iterator_bare, m)?)?;
949        m.add_function(wrap_pyfunction!(struct_log_iterator_unified, m)?)?;
950        m.add_function(wrap_pyfunction!(copperlist_iterator_unified, m)?)?;
951        m.add_function(wrap_pyfunction!(runtime_lifecycle_iterator_unified, m)?)?;
952        Ok(())
953    }
954
955    fn decode_next_copperlist<P>(
956        reader: &mut Box<dyn Read + Send + Sync>,
957        py: Python<'_>,
958    ) -> Option<PyResult<Py<PyAny>>>
959    where
960        P: CopperListTuple,
961    {
962        let entry = super::read_next_entry::<CopperList<P>>(reader)?;
963        Some(copperlist_to_py::<P>(&entry, py))
964    }
965
966    fn copperlist_to_py<P>(entry: &CopperList<P>, py: Python<'_>) -> PyResult<Py<PyAny>>
967    where
968        P: CopperListTuple,
969    {
970        let task_ids = P::get_all_task_ids();
971        let root = PyDict::new(py);
972        root.set_item("id", entry.id)?;
973
974        let mut messages: Vec<Py<PyAny>> = Vec::new();
975        for (idx, msg) in entry.cumsgs().into_iter().enumerate() {
976            let message = PyDict::new(py);
977            message.set_item("task_id", task_ids.get(idx).copied().unwrap_or("unknown"))?;
978            message.set_item("tov", tov_to_py(msg.tov(), py)?)?;
979            message.set_item("metadata", metadata_to_py(msg.metadata(), py)?)?;
980            match msg.payload_reflect() {
981                Some(payload) => message.set_item(
982                    "payload",
983                    partial_reflect_to_py(payload.as_partial_reflect(), py)?,
984                )?,
985                None => message.set_item("payload", py.None())?,
986            }
987            messages.push(dict_to_namespace(message, py)?);
988        }
989
990        root.set_item("messages", PyList::new(py, messages)?)?;
991        dict_to_namespace(root, py)
992    }
993
994    fn runtime_lifecycle_record_to_py(
995        entry: &RuntimeLifecycleRecord,
996        py: Python<'_>,
997    ) -> PyResult<Py<PyAny>> {
998        let root = PyDict::new(py);
999        root.set_item("timestamp_ns", entry.timestamp.as_nanos())?;
1000        root.set_item("event", runtime_lifecycle_event_to_py(&entry.event, py)?)?;
1001        dict_to_namespace(root, py)
1002    }
1003
1004    fn runtime_lifecycle_event_to_py(
1005        event: &RuntimeLifecycleEvent,
1006        py: Python<'_>,
1007    ) -> PyResult<Py<PyAny>> {
1008        let root = PyDict::new(py);
1009        match event {
1010            RuntimeLifecycleEvent::Instantiated {
1011                config_source,
1012                effective_config_ron,
1013                stack,
1014            } => {
1015                root.set_item("kind", "instantiated")?;
1016                root.set_item("config_source", runtime_config_source_to_py(config_source))?;
1017                root.set_item("effective_config_ron", effective_config_ron)?;
1018
1019                let stack_py = PyDict::new(py);
1020                stack_py.set_item("app_name", &stack.app_name)?;
1021                stack_py.set_item("app_version", &stack.app_version)?;
1022                stack_py.set_item("git_commit", &stack.git_commit)?;
1023                stack_py.set_item("git_dirty", stack.git_dirty)?;
1024                stack_py.set_item("subsystem_id", &stack.subsystem_id)?;
1025                stack_py.set_item("subsystem_code", stack.subsystem_code)?;
1026                stack_py.set_item("instance_id", stack.instance_id)?;
1027                root.set_item("stack", dict_to_namespace(stack_py, py)?)?;
1028            }
1029            RuntimeLifecycleEvent::MissionStarted { mission } => {
1030                root.set_item("kind", "mission_started")?;
1031                root.set_item("mission", mission)?;
1032            }
1033            RuntimeLifecycleEvent::MissionStopped { mission, reason } => {
1034                root.set_item("kind", "mission_stopped")?;
1035                root.set_item("mission", mission)?;
1036                root.set_item("reason", reason)?;
1037            }
1038            RuntimeLifecycleEvent::Panic {
1039                message,
1040                file,
1041                line,
1042                column,
1043            } => {
1044                root.set_item("kind", "panic")?;
1045                root.set_item("message", message)?;
1046                root.set_item("file", file)?;
1047                root.set_item("line", line)?;
1048                root.set_item("column", column)?;
1049            }
1050            RuntimeLifecycleEvent::ShutdownCompleted => {
1051                root.set_item("kind", "shutdown_completed")?;
1052            }
1053        }
1054
1055        dict_to_namespace(root, py)
1056    }
1057
1058    fn runtime_config_source_to_py(source: &RuntimeLifecycleConfigSource) -> &'static str {
1059        match source {
1060            RuntimeLifecycleConfigSource::ProgrammaticOverride => "programmatic_override",
1061            RuntimeLifecycleConfigSource::ExternalFile => "external_file",
1062            RuntimeLifecycleConfigSource::BundledDefault => "bundled_default",
1063        }
1064    }
1065
1066    fn metadata_to_py(metadata: &dyn CuMsgMetadataTrait, py: Python<'_>) -> PyResult<Py<PyAny>> {
1067        let process = metadata.process_time();
1068        let start: Option<CuTime> = process.start.into();
1069        let end: Option<CuTime> = process.end.into();
1070
1071        let process_time = PyDict::new(py);
1072        process_time.set_item("start_ns", start.map(|t| t.as_nanos()))?;
1073        process_time.set_item("end_ns", end.map(|t| t.as_nanos()))?;
1074
1075        let metadata_py = PyDict::new(py);
1076        metadata_py.set_item("process_time", dict_to_namespace(process_time, py)?)?;
1077        metadata_py.set_item("status_txt", metadata.status_txt().0.to_string())?;
1078        if let Some(origin) = metadata.origin() {
1079            let origin_py = PyDict::new(py);
1080            origin_py.set_item("subsystem_code", origin.subsystem_code)?;
1081            origin_py.set_item("instance_id", origin.instance_id)?;
1082            origin_py.set_item("cl_id", origin.cl_id)?;
1083            metadata_py.set_item("origin", dict_to_namespace(origin_py, py)?)?;
1084        } else {
1085            metadata_py.set_item("origin", py.None())?;
1086        }
1087        dict_to_namespace(metadata_py, py)
1088    }
1089
1090    fn tov_to_py(tov: Tov, py: Python<'_>) -> PyResult<Py<PyAny>> {
1091        let tov_py = PyDict::new(py);
1092        match tov {
1093            Tov::None => {
1094                tov_py.set_item("kind", "none")?;
1095            }
1096            Tov::Time(t) => {
1097                tov_py.set_item("kind", "time")?;
1098                tov_py.set_item("time_ns", t.as_nanos())?;
1099            }
1100            Tov::Range(r) => {
1101                tov_py.set_item("kind", "range")?;
1102                tov_py.set_item("start_ns", r.start.as_nanos())?;
1103                tov_py.set_item("end_ns", r.end.as_nanos())?;
1104            }
1105        }
1106        dict_to_namespace(tov_py, py)
1107    }
1108
1109    fn partial_reflect_to_py(value: &dyn PartialReflect, py: Python<'_>) -> PyResult<Py<PyAny>> {
1110        #[allow(unreachable_patterns)]
1111        match value.reflect_ref() {
1112            ReflectRef::Struct(s) => struct_to_py(s, py),
1113            ReflectRef::TupleStruct(ts) => tuple_struct_to_py(ts, py),
1114            ReflectRef::Tuple(t) => tuple_to_py(t, py),
1115            ReflectRef::List(list) => list_to_py(list, py),
1116            ReflectRef::Array(array) => array_to_py(array, py),
1117            ReflectRef::Map(map) => map_to_py(map, py),
1118            ReflectRef::Set(set) => set_to_py(set, py),
1119            ReflectRef::Enum(e) => enum_to_py(e, py),
1120            ReflectRef::Opaque(opaque) => opaque_to_py(opaque, py),
1121            _ => Ok(py.None()),
1122        }
1123    }
1124
1125    fn struct_to_py(value: &dyn cu29::bevy_reflect::Struct, py: Python<'_>) -> PyResult<Py<PyAny>> {
1126        let dict = PyDict::new(py);
1127        for idx in 0..value.field_len() {
1128            if let Some(field) = value.field_at(idx) {
1129                let name = value
1130                    .name_at(idx)
1131                    .map(str::to_owned)
1132                    .unwrap_or_else(|| format!("field_{idx}"));
1133                dict.set_item(name, partial_reflect_to_py(field, py)?)?;
1134            }
1135        }
1136
1137        if let Some(unit) = unit_abbrev_for_type_path(value.reflect_type_path())
1138            && let Some(raw_value) = dict.get_item("value")?
1139        {
1140            if let Ok(v) = raw_value.extract::<f64>() {
1141                let unit_value = PyUnitValue {
1142                    value: v,
1143                    unit: unit.to_string(),
1144                };
1145                return Ok(Py::new(py, unit_value)?.into());
1146            }
1147            if let Ok(v) = raw_value.extract::<f32>() {
1148                let unit_value = PyUnitValue {
1149                    value: v as f64,
1150                    unit: unit.to_string(),
1151                };
1152                return Ok(Py::new(py, unit_value)?.into());
1153            }
1154        }
1155
1156        dict_to_namespace(dict, py)
1157    }
1158
1159    fn tuple_struct_to_py(
1160        value: &dyn cu29::bevy_reflect::TupleStruct,
1161        py: Python<'_>,
1162    ) -> PyResult<Py<PyAny>> {
1163        let mut fields = Vec::with_capacity(value.field_len());
1164        for idx in 0..value.field_len() {
1165            if let Some(field) = value.field(idx) {
1166                fields.push(partial_reflect_to_py(field, py)?);
1167            } else {
1168                fields.push(py.None());
1169            }
1170        }
1171        Ok(PyList::new(py, fields)?.into_pyobject(py)?.into())
1172    }
1173
1174    fn tuple_to_py(value: &dyn cu29::bevy_reflect::Tuple, py: Python<'_>) -> PyResult<Py<PyAny>> {
1175        let mut fields = Vec::with_capacity(value.field_len());
1176        for idx in 0..value.field_len() {
1177            if let Some(field) = value.field(idx) {
1178                fields.push(partial_reflect_to_py(field, py)?);
1179            } else {
1180                fields.push(py.None());
1181            }
1182        }
1183        Ok(PyList::new(py, fields)?.into_pyobject(py)?.into())
1184    }
1185
1186    fn list_to_py(value: &dyn cu29::bevy_reflect::List, py: Python<'_>) -> PyResult<Py<PyAny>> {
1187        let mut items = Vec::with_capacity(value.len());
1188        for item in value.iter() {
1189            items.push(partial_reflect_to_py(item, py)?);
1190        }
1191        Ok(PyList::new(py, items)?.into_pyobject(py)?.into())
1192    }
1193
1194    fn array_to_py(value: &dyn cu29::bevy_reflect::Array, py: Python<'_>) -> PyResult<Py<PyAny>> {
1195        let mut items = Vec::with_capacity(value.len());
1196        for item in value.iter() {
1197            items.push(partial_reflect_to_py(item, py)?);
1198        }
1199        Ok(PyList::new(py, items)?.into_pyobject(py)?.into())
1200    }
1201
1202    fn map_to_py(value: &dyn cu29::bevy_reflect::Map, py: Python<'_>) -> PyResult<Py<PyAny>> {
1203        let dict = PyDict::new(py);
1204        for (key, val) in value.iter() {
1205            let key_str = reflect_key_to_string(key);
1206            dict.set_item(key_str, partial_reflect_to_py(val, py)?)?;
1207        }
1208        Ok(dict.into_pyobject(py)?.into())
1209    }
1210
1211    fn set_to_py(value: &dyn cu29::bevy_reflect::Set, py: Python<'_>) -> PyResult<Py<PyAny>> {
1212        let mut items = Vec::with_capacity(value.len());
1213        for item in value.iter() {
1214            items.push(partial_reflect_to_py(item, py)?);
1215        }
1216        Ok(PyList::new(py, items)?.into_pyobject(py)?.into())
1217    }
1218
1219    fn enum_to_py(value: &dyn cu29::bevy_reflect::Enum, py: Python<'_>) -> PyResult<Py<PyAny>> {
1220        let dict = PyDict::new(py);
1221        dict.set_item("variant", value.variant_name())?;
1222
1223        match value.variant_type() {
1224            VariantType::Unit => {}
1225            VariantType::Tuple => {
1226                let mut fields = Vec::with_capacity(value.field_len());
1227                for idx in 0..value.field_len() {
1228                    if let Some(field) = value.field_at(idx) {
1229                        fields.push(partial_reflect_to_py(field, py)?);
1230                    } else {
1231                        fields.push(py.None());
1232                    }
1233                }
1234                dict.set_item("fields", PyList::new(py, fields)?)?;
1235            }
1236            VariantType::Struct => {
1237                let fields = PyDict::new(py);
1238                for idx in 0..value.field_len() {
1239                    if let Some(field) = value.field_at(idx) {
1240                        let name = value
1241                            .name_at(idx)
1242                            .map(str::to_owned)
1243                            .unwrap_or_else(|| format!("field_{idx}"));
1244                        fields.set_item(name, partial_reflect_to_py(field, py)?)?;
1245                    }
1246                }
1247                dict.set_item("fields", fields)?;
1248            }
1249        }
1250
1251        dict_to_namespace(dict, py)
1252    }
1253
1254    fn dict_to_namespace(dict: Bound<'_, PyDict>, py: Python<'_>) -> PyResult<Py<PyAny>> {
1255        let types = py.import("types")?;
1256        let namespace_ctor = types.getattr("SimpleNamespace")?;
1257        let namespace = namespace_ctor.call((), Some(&dict))?;
1258        Ok(namespace.into())
1259    }
1260
1261    fn reflect_key_to_string(value: &dyn PartialReflect) -> String {
1262        if let Some(v) = value.try_downcast_ref::<String>() {
1263            return v.clone();
1264        }
1265        if let Some(v) = value.try_downcast_ref::<&'static str>() {
1266            return (*v).to_string();
1267        }
1268        if let Some(v) = value.try_downcast_ref::<char>() {
1269            return v.to_string();
1270        }
1271        if let Some(v) = value.try_downcast_ref::<bool>() {
1272            return v.to_string();
1273        }
1274        if let Some(v) = value.try_downcast_ref::<u64>() {
1275            return v.to_string();
1276        }
1277        if let Some(v) = value.try_downcast_ref::<i64>() {
1278            return v.to_string();
1279        }
1280        if let Some(v) = value.try_downcast_ref::<usize>() {
1281            return v.to_string();
1282        }
1283        if let Some(v) = value.try_downcast_ref::<isize>() {
1284            return v.to_string();
1285        }
1286        format!("{value:?}")
1287    }
1288
1289    fn unit_abbrev_for_type_path(type_path: &str) -> Option<&'static str> {
1290        match type_path.rsplit("::").next()? {
1291            "Acceleration" => Some("m/s^2"),
1292            "Angle" => Some("rad"),
1293            "AngularVelocity" => Some("rad/s"),
1294            "ElectricPotential" => Some("V"),
1295            "Length" => Some("m"),
1296            "MagneticFluxDensity" => Some("T"),
1297            "Pressure" => Some("Pa"),
1298            "Ratio" => Some("1"),
1299            "ThermodynamicTemperature" => Some("K"),
1300            "Time" => Some("s"),
1301            "Velocity" => Some("m/s"),
1302            _ => None,
1303        }
1304    }
1305
1306    fn opaque_to_py(value: &dyn PartialReflect, py: Python<'_>) -> PyResult<Py<PyAny>> {
1307        macro_rules! downcast_copy {
1308            ($ty:ty) => {
1309                if let Some(v) = value.try_downcast_ref::<$ty>() {
1310                    return Ok(v.into_pyobject(py)?.to_owned().into());
1311                }
1312            };
1313        }
1314
1315        downcast_copy!(bool);
1316        downcast_copy!(u8);
1317        downcast_copy!(u16);
1318        downcast_copy!(u32);
1319        downcast_copy!(u64);
1320        downcast_copy!(u128);
1321        downcast_copy!(usize);
1322        downcast_copy!(i8);
1323        downcast_copy!(i16);
1324        downcast_copy!(i32);
1325        downcast_copy!(i64);
1326        downcast_copy!(i128);
1327        downcast_copy!(isize);
1328        downcast_copy!(f32);
1329        downcast_copy!(f64);
1330        downcast_copy!(char);
1331
1332        if let Some(v) = value.try_downcast_ref::<String>() {
1333            return Ok(v.into_pyobject(py)?.into());
1334        }
1335        if let Some(v) = value.try_downcast_ref::<&'static str>() {
1336            return Ok(v.into_pyobject(py)?.into());
1337        }
1338        if let Some(v) = value.try_downcast_ref::<Vec<u8>>() {
1339            return Ok(v.into_pyobject(py)?.into());
1340        }
1341
1342        let fallback = format!("{value:?}");
1343        Ok(fallback.into_pyobject(py)?.into())
1344    }
1345    fn value_to_py(value: &cu29::prelude::Value, py: Python<'_>) -> PyResult<Py<PyAny>> {
1346        match value {
1347            Value::String(s) => Ok(s.into_pyobject(py)?.into()),
1348            Value::U64(u) => Ok(u.into_pyobject(py)?.into()),
1349            Value::U128(u) => Ok(u.into_pyobject(py)?.into()),
1350            Value::I64(i) => Ok(i.into_pyobject(py)?.into()),
1351            Value::I128(i) => Ok(i.into_pyobject(py)?.into()),
1352            Value::F64(f) => Ok(f.into_pyobject(py)?.into()),
1353            Value::Bool(b) => Ok(b.into_pyobject(py)?.to_owned().into()),
1354            Value::CuTime(t) => Ok(t.0.into_pyobject(py)?.into()),
1355            Value::Bytes(b) => Ok(b.into_pyobject(py)?.into()),
1356            Value::Char(c) => Ok(c.into_pyobject(py)?.into()),
1357            Value::I8(i) => Ok(i.into_pyobject(py)?.into()),
1358            Value::U8(u) => Ok(u.into_pyobject(py)?.into()),
1359            Value::I16(i) => Ok(i.into_pyobject(py)?.into()),
1360            Value::U16(u) => Ok(u.into_pyobject(py)?.into()),
1361            Value::I32(i) => Ok(i.into_pyobject(py)?.into()),
1362            Value::U32(u) => Ok(u.into_pyobject(py)?.into()),
1363            Value::Map(m) => {
1364                let dict = PyDict::new(py);
1365                for (k, v) in m.iter() {
1366                    dict.set_item(value_to_py(k, py)?, value_to_py(v, py)?)?;
1367                }
1368                Ok(dict.into_pyobject(py)?.into())
1369            }
1370            Value::F32(f) => Ok(f.into_pyobject(py)?.into()),
1371            Value::Option(o) => match o.as_ref() {
1372                Some(value) => value_to_py(value, py),
1373                None => Ok(py.None()),
1374            },
1375            Value::Unit => Ok(py.None()),
1376            Value::Newtype(v) => value_to_py(v, py),
1377            Value::Seq(s) => {
1378                let items: Vec<Py<PyAny>> = s
1379                    .iter()
1380                    .map(|value| value_to_py(value, py))
1381                    .collect::<PyResult<_>>()?;
1382                let list = PyList::new(py, items)?;
1383                Ok(list.into_pyobject(py)?.into())
1384            }
1385        }
1386    }
1387
1388    #[cfg(test)]
1389    mod tests {
1390        use super::*;
1391
1392        #[derive(Debug, Default, bincode::Encode, bincode::Decode, serde::Serialize)]
1393        struct EmptyMessages;
1394
1395        impl ErasedCuStampedDataSet for EmptyMessages {
1396            fn cumsgs(&self) -> Vec<&dyn ErasedCuStampedData> {
1397                Vec::new()
1398            }
1399        }
1400
1401        impl MatchingTasks for EmptyMessages {
1402            fn get_all_task_ids() -> &'static [&'static str] {
1403                &[]
1404            }
1405        }
1406
1407        #[test]
1408        fn copperlist_python_export_omits_runtime_state() {
1409            Python::initialize();
1410            Python::attach(|py| {
1411                let list = CopperList::new(7, EmptyMessages);
1412                let value = copperlist_to_py(&list, py).unwrap();
1413                assert!(!value.bind(py).hasattr("state").unwrap());
1414                assert_eq!(
1415                    value
1416                        .bind(py)
1417                        .getattr("id")
1418                        .unwrap()
1419                        .extract::<u64>()
1420                        .unwrap(),
1421                    7
1422                );
1423            });
1424        }
1425
1426        #[test]
1427        fn value_to_py_preserves_128_bit_integers() {
1428            Python::initialize();
1429            Python::attach(|py| {
1430                let u128_value = u128::from(u64::MAX) + 99;
1431                let u128_py = value_to_py(&Value::U128(u128_value), py).unwrap();
1432                assert_eq!(u128_py.bind(py).extract::<u128>().unwrap(), u128_value);
1433
1434                let i128_value = i128::from(i64::MIN) - 99;
1435                let i128_py = value_to_py(&Value::I128(i128_value), py).unwrap();
1436                assert_eq!(i128_py.bind(py).extract::<i128>().unwrap(), i128_value);
1437            });
1438        }
1439    }
1440}
1441
1442#[cfg(test)]
1443mod tests {
1444    use super::*;
1445    use bincode::{Decode, Encode, encode_into_slice};
1446    use serde::Deserialize;
1447    use std::env;
1448    use std::fs;
1449    use std::io::Cursor;
1450    use std::path::PathBuf;
1451    use std::sync::{Arc, Mutex};
1452    use tempfile::{TempDir, tempdir};
1453
1454    fn copy_stringindex_to_temp(tmpdir: &TempDir) -> PathBuf {
1455        // Build a minimal index on the fly so tests don't depend on build-time artifacts.
1456        let fake_out_dir = tmpdir.path().join("build").join("out").join("dir");
1457        fs::create_dir_all(&fake_out_dir).unwrap();
1458        // SAFETY: Tests run single-threaded here and we only read the variable after setting it.
1459        unsafe {
1460            env::set_var("LOG_INDEX_DIR", &fake_out_dir);
1461        }
1462
1463        // Provide entries for the message indexes used in this test module.
1464        let _ = cu29_intern_strs::intern_string("unused to start counter");
1465        let _ = cu29_intern_strs::intern_string("Just a String {}");
1466        let _ = cu29_intern_strs::intern_string("Just a String (low level) {}");
1467        let _ = cu29_intern_strs::intern_string("Just a String (end to end) {}");
1468
1469        let index_dir = cu29_intern_strs::default_log_index_dir();
1470        cu29_intern_strs::read_interned_strings(&index_dir).unwrap();
1471        index_dir
1472    }
1473
1474    #[test]
1475    fn test_extract_low_level_cu29_log() {
1476        let temp_dir = TempDir::new().unwrap();
1477        let temp_path = copy_stringindex_to_temp(&temp_dir);
1478        let entry = CuLogEntry::new(3, CuLogLevel::Info);
1479        let bytes = bincode::encode_to_vec(&entry, standard()).unwrap();
1480        let reader = Cursor::new(bytes.as_slice());
1481        textlog_dump(reader, temp_path.as_path()).unwrap();
1482    }
1483
1484    #[test]
1485    fn end_to_end_datalogger_and_structlog_test() {
1486        let dir = tempdir().expect("Failed to create temp dir");
1487        let path = dir
1488            .path()
1489            .join("end_to_end_datalogger_and_structlog_test.copper");
1490        {
1491            // Write a couple log entries
1492            let UnifiedLogger::Write(logger) = UnifiedLoggerBuilder::new()
1493                .write(true)
1494                .create(true)
1495                .file_base_name(&path)
1496                .preallocated_size(100000)
1497                .build()
1498                .expect("Failed to create logger")
1499            else {
1500                panic!("Failed to create logger")
1501            };
1502            let data_logger = Arc::new(Mutex::new(logger));
1503            let stream = stream_write(data_logger.clone(), UnifiedLogType::StructuredLogLine, 1024)
1504                .expect("Failed to create stream");
1505            let rt = LoggerRuntime::init(RobotClock::default(), stream, None::<NullLog>);
1506
1507            let mut entry = CuLogEntry::new(4, CuLogLevel::Info); // this is a "Just a String {}" log line
1508            entry.add_param(0, Value::String("Parameter for the log line".into()));
1509            log(&mut entry).expect("Failed to log");
1510            let mut entry = CuLogEntry::new(2, CuLogLevel::Info); // this is a "Just a String {}" log line
1511            entry.add_param(0, Value::String("Parameter for the log line".into()));
1512            log(&mut entry).expect("Failed to log");
1513
1514            // everything is dropped here
1515            drop(rt);
1516        }
1517        // Read back the log
1518        let UnifiedLogger::Read(logger) = UnifiedLoggerBuilder::new()
1519            .file_base_name(
1520                &dir.path()
1521                    .join("end_to_end_datalogger_and_structlog_test.copper"),
1522            )
1523            .build()
1524            .expect("Failed to create logger")
1525        else {
1526            panic!("Failed to create logger")
1527        };
1528        let reader = UnifiedLoggerIOReader::new(logger, UnifiedLogType::StructuredLogLine);
1529        let temp_dir = TempDir::new().unwrap();
1530        textlog_dump(
1531            reader,
1532            Path::new(copy_stringindex_to_temp(&temp_dir).as_path()),
1533        )
1534        .expect("Failed to dump log");
1535    }
1536
1537    // This is normally generated at compile time in CuPayload.
1538    #[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize, Encode, Decode, Default)]
1539    struct MyMsgs((u8, i32, f32));
1540
1541    impl ErasedCuStampedDataSet for MyMsgs {
1542        fn cumsgs(&self) -> Vec<&dyn ErasedCuStampedData> {
1543            Vec::new()
1544        }
1545    }
1546
1547    impl MatchingTasks for MyMsgs {
1548        fn get_all_task_ids() -> &'static [&'static str] {
1549            &[]
1550        }
1551    }
1552
1553    /// Checks if we can recover the copper lists from a binary representation.
1554    #[test]
1555    fn test_copperlists_dump() {
1556        let mut data = vec![0u8; 10000];
1557        let mypls: [MyMsgs; 4] = [
1558            MyMsgs((1, 2, 3.0)),
1559            MyMsgs((2, 3, 4.0)),
1560            MyMsgs((3, 4, 5.0)),
1561            MyMsgs((4, 5, 6.0)),
1562        ];
1563
1564        let mut offset: usize = 0;
1565        for pl in mypls.iter() {
1566            let cl = CopperList::<MyMsgs>::new(1, *pl);
1567            offset +=
1568                encode_into_slice(&cl, &mut data.as_mut_slice()[offset..], standard()).unwrap();
1569        }
1570
1571        let reader = Cursor::new(data);
1572
1573        let mut iter = copperlists_reader::<MyMsgs>(reader);
1574        assert_eq!(iter.next().unwrap().msgs, MyMsgs((1, 2, 3.0)));
1575        assert_eq!(iter.next().unwrap().msgs, MyMsgs((2, 3, 4.0)));
1576        assert_eq!(iter.next().unwrap().msgs, MyMsgs((3, 4, 5.0)));
1577        assert_eq!(iter.next().unwrap().msgs, MyMsgs((4, 5, 6.0)));
1578    }
1579
1580    #[test]
1581    fn runtime_lifecycle_reader_extracts_started_mission() {
1582        let records = vec![
1583            RuntimeLifecycleRecord {
1584                timestamp: CuTime::default(),
1585                event: RuntimeLifecycleEvent::Instantiated {
1586                    config_source: RuntimeLifecycleConfigSource::BundledDefault,
1587                    effective_config_ron: "(missions: [])".to_string(),
1588                    stack: RuntimeLifecycleStackInfo {
1589                        app_name: "demo".to_string(),
1590                        app_version: "0.1.0".to_string(),
1591                        git_commit: None,
1592                        git_dirty: None,
1593                        subsystem_id: Some("ping".to_string()),
1594                        subsystem_code: 7,
1595                        instance_id: 42,
1596                    },
1597                },
1598            },
1599            RuntimeLifecycleRecord {
1600                timestamp: CuTime::from_nanos(42),
1601                event: RuntimeLifecycleEvent::MissionStarted {
1602                    mission: "gnss".to_string(),
1603                },
1604            },
1605        ];
1606        let mut bytes = Vec::new();
1607        for record in &records {
1608            bytes.extend(bincode::encode_to_vec(record, standard()).unwrap());
1609        }
1610
1611        let mission =
1612            runtime_lifecycle_reader(Cursor::new(bytes)).find_map(|entry| match entry.event {
1613                RuntimeLifecycleEvent::MissionStarted { mission } => Some(mission),
1614                _ => None,
1615            });
1616        assert_eq!(mission.as_deref(), Some("gnss"));
1617    }
1618
1619    #[test]
1620    fn logstats_mission_defaults_to_log_then_named_default_then_first() {
1621        let config = CuConfig::deserialize_ron(
1622            r#"(
1623                missions: [(id: "zeta"), (id: "default"), (id: "alpha")],
1624                tasks: [],
1625                cnx: [],
1626            )"#,
1627        )
1628        .unwrap();
1629        assert_eq!(
1630            resolve_logstats_mission(&config, None, Some("zeta".to_string())).as_deref(),
1631            Some("zeta")
1632        );
1633        assert_eq!(
1634            resolve_logstats_mission(&config, None, Some("missing".to_string())).as_deref(),
1635            Some("default")
1636        );
1637        assert_eq!(
1638            resolve_logstats_mission(&config, Some("alpha".to_string()), None).as_deref(),
1639            Some("alpha")
1640        );
1641
1642        let config = CuConfig::deserialize_ron(
1643            r#"(
1644                missions: [(id: "zeta"), (id: "alpha")],
1645                tasks: [],
1646                cnx: [],
1647            )"#,
1648        )
1649        .unwrap();
1650        assert_eq!(
1651            resolve_logstats_mission(&config, None, None).as_deref(),
1652            Some("alpha")
1653        );
1654    }
1655}