-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathlib.rs
More file actions
1473 lines (1341 loc) · 52.9 KB
/
lib.rs
File metadata and controls
1473 lines (1341 loc) · 52.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
mod fsck;
pub mod logstats;
#[cfg(feature = "mcap")]
pub mod mcap_export;
#[cfg(feature = "mcap")]
pub mod serde_to_jsonschema;
use bincode::Decode;
use bincode::config::standard;
use bincode::decode_from_std_read;
use bincode::error::DecodeError;
use clap::{Parser, Subcommand, ValueEnum};
use cu29::UnifiedLogType;
use cu29::prelude::*;
use cu29_intern_strs::read_interned_strings;
use fsck::check;
#[cfg(feature = "mcap")]
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
use logstats::{compute_logstats, write_logstats};
use serde::Serialize;
use std::fmt::{Display, Formatter};
#[cfg(feature = "mcap")]
use std::io::IsTerminal;
use std::io::Read;
use std::path::{Path, PathBuf};
#[cfg(feature = "mcap")]
pub use mcap_export::{
McapExportStats, PayloadSchemas, export_to_mcap, export_to_mcap_with_schemas, mcap_info,
};
#[cfg(feature = "mcap")]
pub use serde_to_jsonschema::trace_type_to_jsonschema;
#[cfg(all(feature = "python", not(target_os = "macos")))]
pub use python::register_copperlist_python_type;
/// Creates a Python CopperList iterator for a specific CopperList tuple type.
///
/// This is intended for app-specific Python modules that know their generated
/// CopperList type at compile time.
#[cfg(all(feature = "python", not(target_os = "macos")))]
pub fn copperlist_iterator_unified_typed_py<P>(
unified_src_path: &str,
py: pyo3::Python<'_>,
) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>>
where
P: CopperListTuple,
{
register_copperlist_python_type::<P>()
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
let iter = python::copperlist_iterator_unified(unified_src_path)?;
pyo3::Py::new(py, iter).map(|obj| obj.into())
}
/// Creates a Python RuntimeLifecycle iterator from a unified log.
#[cfg(all(feature = "python", not(target_os = "macos")))]
pub fn runtime_lifecycle_iterator_unified_py(
unified_src_path: &str,
py: pyo3::Python<'_>,
) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
let iter = python::runtime_lifecycle_iterator_unified(unified_src_path)?;
pyo3::Py::new(py, iter).map(|obj| obj.into())
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
pub enum ExportFormat {
Json,
Csv,
}
impl Display for ExportFormat {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ExportFormat::Json => write!(f, "json"),
ExportFormat::Csv => write!(f, "csv"),
}
}
}
/// This is a generator for a main function to build a log extractor.
#[derive(Parser)]
#[command(author, version, about)]
pub struct LogReaderCli {
/// The base path is the name with no _0 _1 et the end.
/// for example for toto_0.copper, toto_1.copper ... the base name is toto.copper
pub unifiedlog_base: PathBuf,
#[command(subcommand)]
pub command: Command,
}
#[derive(Subcommand)]
pub enum Command {
/// Extract logs
ExtractTextLog { log_index: PathBuf },
/// Extract copperlists
ExtractCopperlists {
#[arg(short, long, default_value_t = ExportFormat::Json)]
export_format: ExportFormat,
},
/// Check the log and dump info about it.
Fsck {
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
/// Decode and print RuntimeLifecycle events.
#[arg(long)]
dump_runtime_lifecycle: bool,
},
/// Export log statistics to JSON for offline DAG rendering.
LogStats {
/// Output JSON file path
#[arg(short, long, default_value = "cu29_logstats.json")]
output: PathBuf,
/// Config file used to map outputs to edges
#[arg(long, default_value = "copperconfig.ron")]
config: PathBuf,
/// Mission id to use when reading the config
#[arg(long)]
mission: Option<String>,
},
/// Export copperlists to MCAP format (requires 'mcap' feature)
#[cfg(feature = "mcap")]
ExportMcap {
/// Output MCAP file path
#[arg(short, long)]
output: PathBuf,
/// Force progress bar even when stderr is not a TTY
#[arg(long)]
progress: bool,
/// Suppress the progress bar
#[arg(long)]
quiet: bool,
},
/// Inspect an MCAP file and dump metadata, schemas, and stats (requires 'mcap' feature)
#[cfg(feature = "mcap")]
McapInfo {
/// Path to the MCAP file to inspect
mcap_file: PathBuf,
/// Show full schema content
#[arg(short, long)]
schemas: bool,
/// Show sample messages (first N messages per channel)
#[arg(short = 'n', long, default_value_t = 0)]
sample_messages: usize,
},
}
fn write_json_pretty<T: Serialize + ?Sized>(value: &T) -> CuResult<()> {
serde_json::to_writer_pretty(std::io::stdout(), value)
.map_err(|e| CuError::new_with_cause("Failed to write JSON output", e))
}
fn write_json<T: Serialize + ?Sized>(value: &T) -> CuResult<()> {
serde_json::to_writer(std::io::stdout(), value)
.map_err(|e| CuError::new_with_cause("Failed to write JSON output", e))
}
fn build_read_logger(unifiedlog_base: &Path) -> CuResult<UnifiedLoggerRead> {
let logger = UnifiedLoggerBuilder::new()
.file_base_name(unifiedlog_base)
.build()
.map_err(|e| CuError::new_with_cause("Failed to create logger", e))?;
match logger {
UnifiedLogger::Read(dl) => Ok(dl),
UnifiedLogger::Write(_) => Err(CuError::from(
"Expected read-only unified logger in export CLI",
)),
}
}
/// This is a generator for a main function to build a log extractor.
/// It depends on the specific type of the CopperList payload that is determined at compile time from the configuration.
///
/// When the `mcap` feature is enabled, P must also implement `PayloadSchemas` for MCAP export support.
#[cfg(feature = "mcap")]
pub fn run_cli<P>() -> CuResult<()>
where
P: CopperListTuple + CuPayloadRawBytes + mcap_export::PayloadSchemas,
{
#[cfg(all(feature = "python", not(target_os = "macos")))]
let _ = python::register_copperlist_python_type::<P>();
run_cli_inner::<P>()
}
/// This is a generator for a main function to build a log extractor.
/// It depends on the specific type of the CopperList payload that is determined at compile time from the configuration.
#[cfg(not(feature = "mcap"))]
pub fn run_cli<P>() -> CuResult<()>
where
P: CopperListTuple + CuPayloadRawBytes,
{
#[cfg(all(feature = "python", not(target_os = "macos")))]
let _ = python::register_copperlist_python_type::<P>();
run_cli_inner::<P>()
}
#[cfg(feature = "mcap")]
fn run_cli_inner<P>() -> CuResult<()>
where
P: CopperListTuple + CuPayloadRawBytes + mcap_export::PayloadSchemas,
{
let args = LogReaderCli::parse();
let unifiedlog_base = args.unifiedlog_base;
let mut dl = build_read_logger(&unifiedlog_base)?;
match args.command {
Command::ExtractTextLog { log_index } => {
let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::StructuredLogLine);
textlog_dump(reader, &log_index)?;
}
Command::ExtractCopperlists { export_format } => {
println!("Extracting copperlists with format: {export_format}");
let mut reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::CopperList);
let iter = copperlists_reader::<P>(&mut reader);
match export_format {
ExportFormat::Json => {
for entry in iter {
write_json_pretty(&entry)?;
}
}
ExportFormat::Csv => {
let mut first = true;
for origin in P::get_all_task_ids() {
if !first {
print!(", ");
} else {
print!("id, ");
}
print!("{origin}_time, {origin}_tov, {origin},");
first = false;
}
println!();
for entry in iter {
let mut first = true;
for msg in entry.cumsgs() {
if let Some(payload) = msg.payload() {
if !first {
print!(", ");
} else {
print!("{}, ", entry.id);
}
let metadata = msg.metadata();
print!("{}, {}, ", metadata.process_time(), msg.tov());
write_json(payload)?; // TODO: escape for CSV
first = false;
}
}
println!();
}
}
}
}
Command::Fsck {
verbose,
dump_runtime_lifecycle,
} => {
if let Some(value) = check::<P>(&mut dl, verbose, dump_runtime_lifecycle) {
return value;
}
}
Command::LogStats {
output,
config,
mission,
} => {
run_logstats::<P>(dl, output, config, mission)?;
}
#[cfg(feature = "mcap")]
Command::ExportMcap {
output,
progress,
quiet,
} => {
println!("Exporting copperlists to MCAP format: {}", output.display());
let show_progress = should_show_progress(progress, quiet);
let total_bytes = if show_progress {
Some(copperlist_total_bytes(&unifiedlog_base)?)
} else {
None
};
let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::CopperList);
// Export to MCAP with schemas.
// Note: P must implement PayloadSchemas and provide schemas for each CopperList slot.
let stats = if let Some(total_bytes) = total_bytes {
let progress_bar = make_progress_bar(total_bytes);
let reader = ProgressReader::new(reader, progress_bar.clone());
let result = export_to_mcap_impl::<P>(reader, &output);
progress_bar.finish_and_clear();
result?
} else {
export_to_mcap_impl::<P>(reader, &output)?
};
println!("{stats}");
}
#[cfg(feature = "mcap")]
Command::McapInfo {
mcap_file,
schemas,
sample_messages,
} => {
mcap_info(&mcap_file, schemas, sample_messages)?;
}
}
Ok(())
}
#[cfg(not(feature = "mcap"))]
fn run_cli_inner<P>() -> CuResult<()>
where
P: CopperListTuple + CuPayloadRawBytes,
{
let args = LogReaderCli::parse();
let unifiedlog_base = args.unifiedlog_base;
let mut dl = build_read_logger(&unifiedlog_base)?;
match args.command {
Command::ExtractTextLog { log_index } => {
let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::StructuredLogLine);
textlog_dump(reader, &log_index)?;
}
Command::ExtractCopperlists { export_format } => {
println!("Extracting copperlists with format: {export_format}");
let mut reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::CopperList);
let iter = copperlists_reader::<P>(&mut reader);
match export_format {
ExportFormat::Json => {
for entry in iter {
write_json_pretty(&entry)?;
}
}
ExportFormat::Csv => {
let mut first = true;
for origin in P::get_all_task_ids() {
if !first {
print!(", ");
} else {
print!("id, ");
}
print!("{origin}_time, {origin}_tov, {origin},");
first = false;
}
println!();
for entry in iter {
let mut first = true;
for msg in entry.cumsgs() {
if let Some(payload) = msg.payload() {
if !first {
print!(", ");
} else {
print!("{}, ", entry.id);
}
let metadata = msg.metadata();
print!("{}, {}, ", metadata.process_time(), msg.tov());
write_json(payload)?;
first = false;
}
}
println!();
}
}
}
}
Command::Fsck {
verbose,
dump_runtime_lifecycle,
} => {
if let Some(value) = check::<P>(&mut dl, verbose, dump_runtime_lifecycle) {
return value;
}
}
Command::LogStats {
output,
config,
mission,
} => {
run_logstats::<P>(dl, output, config, mission)?;
}
}
Ok(())
}
fn run_logstats<P>(
dl: UnifiedLoggerRead,
output: PathBuf,
config: PathBuf,
mission: Option<String>,
) -> CuResult<()>
where
P: CopperListTuple + CuPayloadRawBytes,
{
let config_path = config
.to_str()
.ok_or_else(|| CuError::from("Config path is not valid UTF-8"))?;
let cfg = read_configuration(config_path)
.map_err(|e| CuError::new_with_cause("Failed to read configuration", e))?;
let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::CopperList);
let stats = compute_logstats::<P>(reader, &cfg, mission.as_deref())?;
write_logstats(&stats, &output)
}
/// Helper function for MCAP export.
///
/// Uses the PayloadSchemas trait to get per-slot payload schemas.
#[cfg(feature = "mcap")]
fn export_to_mcap_impl<P>(src: impl Read, output: &Path) -> CuResult<McapExportStats>
where
P: CopperListTuple + mcap_export::PayloadSchemas,
{
mcap_export::export_to_mcap::<P, _>(src, output)
}
#[cfg(feature = "mcap")]
struct ProgressReader<R> {
inner: R,
progress: ProgressBar,
}
#[cfg(feature = "mcap")]
impl<R> ProgressReader<R> {
fn new(inner: R, progress: ProgressBar) -> Self {
Self { inner, progress }
}
}
#[cfg(feature = "mcap")]
impl<R: Read> Read for ProgressReader<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let read = self.inner.read(buf)?;
if read > 0 {
self.progress.inc(read as u64);
}
Ok(read)
}
}
#[cfg(feature = "mcap")]
fn make_progress_bar(total_bytes: u64) -> ProgressBar {
let progress_bar = ProgressBar::new(total_bytes);
progress_bar.set_draw_target(ProgressDrawTarget::stderr_with_hz(5));
let style = ProgressStyle::with_template(
"[{elapsed_precise}] {bar:40} {bytes}/{total_bytes} ({bytes_per_sec}, ETA {eta})",
)
.unwrap_or_else(|_| ProgressStyle::default_bar());
progress_bar.set_style(style.progress_chars("=>-"));
progress_bar
}
#[cfg(feature = "mcap")]
fn should_show_progress(force_progress: bool, quiet: bool) -> bool {
!quiet && (force_progress || std::io::stderr().is_terminal())
}
#[cfg(feature = "mcap")]
fn copperlist_total_bytes(log_base: &Path) -> CuResult<u64> {
let mut reader = UnifiedLoggerRead::new(log_base)
.map_err(|e| CuError::new_with_cause("Failed to open log for progress estimation", e))?;
reader
.scan_section_bytes(UnifiedLogType::CopperList)
.map_err(|e| CuError::new_with_cause("Failed to scan log for progress estimation", e))
}
fn read_next_entry<T: Decode<()>>(src: &mut impl Read) -> Option<T> {
let entry = decode_from_std_read::<T, _, _>(src, standard());
match entry {
Ok(entry) => Some(entry),
Err(DecodeError::UnexpectedEnd { .. }) => None,
Err(DecodeError::Io { inner, additional }) => {
if inner.kind() == std::io::ErrorKind::UnexpectedEof {
None
} else {
println!("Error {inner:?} additional:{additional}");
None
}
}
Err(e) => {
println!("Error {e:?}");
None
}
}
}
/// Extracts the copper lists from a binary representation.
/// P is the Payload determined by the configuration of the application.
pub fn copperlists_reader<P: CopperListTuple>(
mut src: impl Read,
) -> impl Iterator<Item = CopperList<P>> {
std::iter::from_fn(move || read_next_entry::<CopperList<P>>(&mut src))
}
/// Extracts the keyframes from the log.
pub fn keyframes_reader(mut src: impl Read) -> impl Iterator<Item = KeyFrame> {
std::iter::from_fn(move || read_next_entry::<KeyFrame>(&mut src))
}
/// Extracts the runtime lifecycle records from the log.
pub fn runtime_lifecycle_reader(
mut src: impl Read,
) -> impl Iterator<Item = RuntimeLifecycleRecord> {
std::iter::from_fn(move || read_next_entry::<RuntimeLifecycleRecord>(&mut src))
}
/// Returns the first mission announced by the runtime lifecycle section, if any.
pub fn unified_log_mission(unifiedlog_base: &Path) -> CuResult<Option<String>> {
let dl = build_read_logger(unifiedlog_base)?;
let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::RuntimeLifecycle);
Ok(
runtime_lifecycle_reader(reader).find_map(|entry| match entry.event {
RuntimeLifecycleEvent::MissionStarted { mission } => Some(mission),
_ => None,
}),
)
}
/// Ensures the unified log was recorded for the expected mission.
pub fn assert_unified_log_mission(unifiedlog_base: &Path, expected_mission: &str) -> CuResult<()> {
match unified_log_mission(unifiedlog_base)? {
Some(actual_mission) if actual_mission == expected_mission => Ok(()),
Some(actual_mission) => Err(CuError::from(format!(
"Mission mismatch: expected '{expected_mission}', found '{actual_mission}'"
))),
None => Err(CuError::from(format!(
"No MissionStarted runtime lifecycle event found while validating expected mission '{expected_mission}'"
))),
}
}
pub fn structlog_reader(mut src: impl Read) -> impl Iterator<Item = CuResult<CuLogEntry>> {
std::iter::from_fn(move || {
let entry = decode_from_std_read::<CuLogEntry, _, _>(&mut src, standard());
match entry {
Err(DecodeError::UnexpectedEnd { .. }) => None,
Err(DecodeError::Io {
inner,
additional: _,
}) => {
if inner.kind() == std::io::ErrorKind::UnexpectedEof {
None
} else {
Some(Err(CuError::new_with_cause("Error reading log", inner)))
}
}
Err(e) => Some(Err(CuError::new_with_cause("Error reading log", e))),
Ok(entry) => {
if entry.msg_index == 0 {
None
} else {
Some(Ok(entry))
}
}
}
})
}
/// Full dump of the copper structured log from its binary representation.
/// This rebuilds a textual log.
/// src: the source of the log data
/// index: the path to the index file (containing the interned strings constructed at build time)
pub fn textlog_dump(src: impl Read, index: &Path) -> CuResult<()> {
let all_strings = read_interned_strings(index).map_err(|e| {
CuError::new_with_cause(
"Failed to read interned strings from index",
std::io::Error::other(e),
)
})?;
for result in structlog_reader(src) {
match result {
Ok(entry) => match rebuild_logline(&all_strings, &entry) {
Ok(line) => println!("{line}"),
Err(e) => println!("Failed to rebuild log line: {e:?}"),
},
Err(e) => return Err(e),
}
}
Ok(())
}
// only for users opting into python interface, not supported on macOS at the moment
#[cfg(all(feature = "python", not(target_os = "macos")))]
mod python {
use bincode::config::standard;
use bincode::decode_from_std_read;
use bincode::error::DecodeError;
use cu29::bevy_reflect::{PartialReflect, ReflectRef, VariantType};
use cu29::prelude::*;
use cu29_intern_strs::read_interned_strings;
use pyo3::exceptions::{PyIOError, PyRuntimeError};
use pyo3::prelude::*;
use pyo3::types::{PyDelta, PyDict, PyList};
use std::io::Read;
use std::path::Path;
use std::sync::OnceLock;
type CopperListDecodeFn =
for<'py> fn(&mut Box<dyn Read + Send + Sync>, Python<'py>) -> Option<PyResult<Py<PyAny>>>;
static COPPERLIST_DECODER: OnceLock<CopperListDecodeFn> = OnceLock::new();
#[pyclass]
pub struct PyLogIterator {
reader: Box<dyn Read + Send + Sync>,
}
#[pyclass]
pub struct PyCopperListIterator {
reader: Box<dyn Read + Send + Sync>,
decode_next: CopperListDecodeFn,
}
#[pyclass]
pub struct PyRuntimeLifecycleIterator {
reader: Box<dyn Read + Send + Sync>,
}
#[pyclass(get_all)]
pub struct PyUnitValue {
pub value: f64,
pub unit: String,
}
pub fn register_copperlist_python_type<P>() -> CuResult<()>
where
P: CopperListTuple,
{
if COPPERLIST_DECODER.get().is_none() {
COPPERLIST_DECODER
.set(decode_next_copperlist::<P>)
.map_err(|_| CuError::from("Failed to register CopperList Python decoder"))?;
}
Ok(())
}
#[pymethods]
impl PyLogIterator {
fn __iter__(slf: PyRefMut<Self>) -> PyRefMut<Self> {
slf
}
fn __next__(mut slf: PyRefMut<Self>) -> Option<PyResult<PyCuLogEntry>> {
match decode_from_std_read::<CuLogEntry, _, _>(&mut slf.reader, standard()) {
Ok(entry) => {
if entry.msg_index == 0 {
None
} else {
Some(Ok(PyCuLogEntry { inner: entry }))
}
}
Err(DecodeError::UnexpectedEnd { .. }) => None,
Err(DecodeError::Io { inner, .. })
if inner.kind() == std::io::ErrorKind::UnexpectedEof =>
{
None
}
Err(e) => Some(Err(PyIOError::new_err(e.to_string()))),
}
}
}
#[pymethods]
impl PyCopperListIterator {
fn __iter__(slf: PyRefMut<Self>) -> PyRefMut<Self> {
slf
}
fn __next__(mut slf: PyRefMut<Self>, py: Python<'_>) -> Option<PyResult<Py<PyAny>>> {
(slf.decode_next)(&mut slf.reader, py)
}
}
#[pymethods]
impl PyRuntimeLifecycleIterator {
fn __iter__(slf: PyRefMut<Self>) -> PyRefMut<Self> {
slf
}
fn __next__(mut slf: PyRefMut<Self>, py: Python<'_>) -> Option<PyResult<Py<PyAny>>> {
let entry = super::read_next_entry::<RuntimeLifecycleRecord>(&mut slf.reader)?;
Some(runtime_lifecycle_record_to_py(&entry, py))
}
}
/// Creates an iterator of CuLogEntries from a bare binary structured log file (ie. not within a unified log).
/// This is mainly used for using the structured logging out of the Copper framework.
/// it returns a tuple with the iterator of log entries and the list of interned strings.
#[pyfunction]
pub fn struct_log_iterator_bare(
bare_struct_src_path: &str,
index_path: &str,
) -> PyResult<(PyLogIterator, Vec<String>)> {
let file = std::fs::File::open(bare_struct_src_path)
.map_err(|e| PyIOError::new_err(e.to_string()))?;
let all_strings = read_interned_strings(Path::new(index_path))
.map_err(|e| PyIOError::new_err(e.to_string()))?;
Ok((
PyLogIterator {
reader: Box::new(file),
},
all_strings,
))
}
/// Creates an iterator of CuLogEntries from a unified log file.
/// This function allows you to easily use python to datamind Copper's structured text logs.
/// it returns a tuple with the iterator of log entries and the list of interned strings.
#[pyfunction]
pub fn struct_log_iterator_unified(
unified_src_path: &str,
index_path: &str,
) -> PyResult<(PyLogIterator, Vec<String>)> {
let all_strings = read_interned_strings(Path::new(index_path))
.map_err(|e| PyIOError::new_err(e.to_string()))?;
let logger = UnifiedLoggerBuilder::new()
.file_base_name(Path::new(unified_src_path))
.build()
.map_err(|e| PyIOError::new_err(e.to_string()))?;
let dl = match logger {
UnifiedLogger::Read(dl) => dl,
UnifiedLogger::Write(_) => {
return Err(PyIOError::new_err(
"Expected read-only unified logger for Python export",
));
}
};
let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::StructuredLogLine);
Ok((
PyLogIterator {
reader: Box::new(reader),
},
all_strings,
))
}
/// Creates an iterator over CopperLists from a unified log file.
/// The concrete CopperList tuple type must be registered from Rust first with
/// `register_copperlist_python_type::<P>()`.
#[pyfunction]
pub fn copperlist_iterator_unified(unified_src_path: &str) -> PyResult<PyCopperListIterator> {
let decode_next = *COPPERLIST_DECODER.get().ok_or_else(|| {
PyRuntimeError::new_err(
"CopperList decoder is not registered. \
Call register_copperlist_python_type::<P>() from Rust before using this function.",
)
})?;
let logger = UnifiedLoggerBuilder::new()
.file_base_name(Path::new(unified_src_path))
.build()
.map_err(|e| PyIOError::new_err(e.to_string()))?;
let dl = match logger {
UnifiedLogger::Read(dl) => dl,
UnifiedLogger::Write(_) => {
return Err(PyIOError::new_err(
"Expected read-only unified logger for Python export",
));
}
};
let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::CopperList);
Ok(PyCopperListIterator {
reader: Box::new(reader),
decode_next,
})
}
/// Creates an iterator over runtime lifecycle records from a unified log file.
#[pyfunction]
pub fn runtime_lifecycle_iterator_unified(
unified_src_path: &str,
) -> PyResult<PyRuntimeLifecycleIterator> {
let logger = UnifiedLoggerBuilder::new()
.file_base_name(Path::new(unified_src_path))
.build()
.map_err(|e| PyIOError::new_err(e.to_string()))?;
let dl = match logger {
UnifiedLogger::Read(dl) => dl,
UnifiedLogger::Write(_) => {
return Err(PyIOError::new_err(
"Expected read-only unified logger for Python export",
));
}
};
let reader = UnifiedLoggerIOReader::new(dl, UnifiedLogType::RuntimeLifecycle);
Ok(PyRuntimeLifecycleIterator {
reader: Box::new(reader),
})
}
/// This is a python wrapper for CuLogEntries.
#[pyclass]
pub struct PyCuLogEntry {
pub inner: CuLogEntry,
}
#[pymethods]
impl PyCuLogEntry {
/// Returns the timestamp of the log entry.
pub fn ts<'a>(&self, py: Python<'a>) -> PyResult<Bound<'a, PyDelta>> {
let nanoseconds: u64 = self.inner.time.into();
// Convert nanoseconds to seconds and microseconds
let days = (nanoseconds / 86_400_000_000_000) as i32;
let seconds = (nanoseconds / 1_000_000_000) as i32;
let microseconds = ((nanoseconds % 1_000_000_000) / 1_000) as i32;
PyDelta::new(py, days, seconds, microseconds, false)
}
/// Returns the index of the message in the vector of interned strings.
pub fn msg_index(&self) -> u32 {
self.inner.msg_index
}
/// Returns the index of the parameter names in the vector of interned strings.
pub fn paramname_indexes(&self) -> Vec<u32> {
self.inner.paramname_indexes.iter().copied().collect()
}
/// Returns the parameters of this log line
pub fn params(&self, py: Python<'_>) -> PyResult<Vec<Py<PyAny>>> {
self.inner
.params
.iter()
.map(|value| value_to_py(value, py))
.collect()
}
}
/// This needs to match the name of the generated '.so'
#[pymodule(name = "libcu29_export")]
fn cu29_export(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyCuLogEntry>()?;
m.add_class::<PyLogIterator>()?;
m.add_class::<PyCopperListIterator>()?;
m.add_class::<PyRuntimeLifecycleIterator>()?;
m.add_class::<PyUnitValue>()?;
m.add_function(wrap_pyfunction!(struct_log_iterator_bare, m)?)?;
m.add_function(wrap_pyfunction!(struct_log_iterator_unified, m)?)?;
m.add_function(wrap_pyfunction!(copperlist_iterator_unified, m)?)?;
m.add_function(wrap_pyfunction!(runtime_lifecycle_iterator_unified, m)?)?;
Ok(())
}
fn decode_next_copperlist<P>(
reader: &mut Box<dyn Read + Send + Sync>,
py: Python<'_>,
) -> Option<PyResult<Py<PyAny>>>
where
P: CopperListTuple,
{
let entry = super::read_next_entry::<CopperList<P>>(reader)?;
Some(copperlist_to_py::<P>(&entry, py))
}
fn copperlist_to_py<P>(entry: &CopperList<P>, py: Python<'_>) -> PyResult<Py<PyAny>>
where
P: CopperListTuple,
{
let task_ids = P::get_all_task_ids();
let root = PyDict::new(py);
root.set_item("id", entry.id)?;
root.set_item("state", entry.get_state().to_string())?;
let mut messages: Vec<Py<PyAny>> = Vec::new();
for (idx, msg) in entry.cumsgs().into_iter().enumerate() {
let message = PyDict::new(py);
message.set_item("task_id", task_ids.get(idx).copied().unwrap_or("unknown"))?;
message.set_item("tov", tov_to_py(msg.tov(), py)?)?;
message.set_item("metadata", metadata_to_py(msg.metadata(), py)?)?;
match msg.payload_reflect() {
Some(payload) => message.set_item(
"payload",
partial_reflect_to_py(payload.as_partial_reflect(), py)?,
)?,
None => message.set_item("payload", py.None())?,
}
messages.push(dict_to_namespace(message, py)?);
}
root.set_item("messages", PyList::new(py, messages)?)?;
dict_to_namespace(root, py)
}
fn runtime_lifecycle_record_to_py(
entry: &RuntimeLifecycleRecord,
py: Python<'_>,
) -> PyResult<Py<PyAny>> {
let root = PyDict::new(py);
root.set_item("timestamp_ns", entry.timestamp.as_nanos())?;
root.set_item("event", runtime_lifecycle_event_to_py(&entry.event, py)?)?;
dict_to_namespace(root, py)
}
fn runtime_lifecycle_event_to_py(
event: &RuntimeLifecycleEvent,
py: Python<'_>,
) -> PyResult<Py<PyAny>> {
let root = PyDict::new(py);
match event {
RuntimeLifecycleEvent::Instantiated {
config_source,
effective_config_ron,
stack,
} => {
root.set_item("kind", "instantiated")?;
root.set_item("config_source", runtime_config_source_to_py(config_source))?;
root.set_item("effective_config_ron", effective_config_ron)?;
let stack_py = PyDict::new(py);
stack_py.set_item("app_name", &stack.app_name)?;
stack_py.set_item("app_version", &stack.app_version)?;
stack_py.set_item("git_commit", &stack.git_commit)?;
stack_py.set_item("git_dirty", stack.git_dirty)?;
root.set_item("stack", dict_to_namespace(stack_py, py)?)?;
}
RuntimeLifecycleEvent::MissionStarted { mission } => {
root.set_item("kind", "mission_started")?;
root.set_item("mission", mission)?;
}
RuntimeLifecycleEvent::MissionStopped { mission, reason } => {
root.set_item("kind", "mission_stopped")?;
root.set_item("mission", mission)?;
root.set_item("reason", reason)?;
}
RuntimeLifecycleEvent::Panic {
message,
file,
line,
column,
} => {
root.set_item("kind", "panic")?;
root.set_item("message", message)?;
root.set_item("file", file)?;
root.set_item("line", line)?;
root.set_item("column", column)?;
}
RuntimeLifecycleEvent::ShutdownCompleted => {
root.set_item("kind", "shutdown_completed")?;
}
}
dict_to_namespace(root, py)
}
fn runtime_config_source_to_py(source: &RuntimeLifecycleConfigSource) -> &'static str {
match source {
RuntimeLifecycleConfigSource::ProgrammaticOverride => "programmatic_override",
RuntimeLifecycleConfigSource::ExternalFile => "external_file",
RuntimeLifecycleConfigSource::BundledDefault => "bundled_default",
}
}
fn metadata_to_py(metadata: &dyn CuMsgMetadataTrait, py: Python<'_>) -> PyResult<Py<PyAny>> {
let process = metadata.process_time();
let start: Option<CuTime> = process.start.into();
let end: Option<CuTime> = process.end.into();
let process_time = PyDict::new(py);
process_time.set_item("start_ns", start.map(|t| t.as_nanos()))?;
process_time.set_item("end_ns", end.map(|t| t.as_nanos()))?;
let metadata_py = PyDict::new(py);
metadata_py.set_item("process_time", dict_to_namespace(process_time, py)?)?;
metadata_py.set_item("status_txt", metadata.status_txt().0.to_string())?;
dict_to_namespace(metadata_py, py)
}
fn tov_to_py(tov: Tov, py: Python<'_>) -> PyResult<Py<PyAny>> {
let tov_py = PyDict::new(py);
match tov {
Tov::None => {
tov_py.set_item("kind", "none")?;
}
Tov::Time(t) => {
tov_py.set_item("kind", "time")?;
tov_py.set_item("time_ns", t.as_nanos())?;
}
Tov::Range(r) => {
tov_py.set_item("kind", "range")?;
tov_py.set_item("start_ns", r.start.as_nanos())?;
tov_py.set_item("end_ns", r.end.as_nanos())?;
}
}
dict_to_namespace(tov_py, py)
}