cu29-export 1.3.0

This is the library support to build log exports for the copper project. It cannot be used independently from the copper project.
Documentation
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
//! Recorded run discovery and bounded access to a selected run's sections.

use crate::build_read_logger;
use bincode::config::standard;
use bincode::decode_from_slice;
use cu29::prelude::CuError;
use cu29::prelude::CuResult;
use cu29::prelude::CuTime;
use cu29::prelude::MainHeader;
use cu29::prelude::RuntimeLifecycleEvent;
use cu29::prelude::RuntimeLifecycleRecord;
use cu29::prelude::RuntimeLifecycleStackInfo;
use cu29::prelude::SectionHeader;
use cu29::prelude::UnifiedLogRead;
use cu29::prelude::UnifiedLogType;
use cu29::prelude::UnifiedLoggerRead;
use cu29::prelude::memmap::LogPosition;
use std::io::{self, Read};
use std::path::Path;

#[derive(Debug)]
pub(crate) struct RecordedRun {
    pub index: usize,
    pub run_id: u64,
    pub mission_index: u32,
    pub started_at: Option<CuTime>,
    pub stack: Option<RuntimeLifecycleStackInfo>,
    pub config: Option<String>,
    pub missions: Vec<String>,
    pub shutdown_completed: bool,
    start: LogPosition,
    pub copperlist_bytes: u64,
}

impl RecordedRun {
    fn new(index: usize, start: LogPosition) -> Self {
        Self {
            index,
            run_id: 0,
            mission_index: 0,
            started_at: None,
            stack: None,
            config: None,
            missions: Vec::new(),
            shutdown_completed: false,
            start,
            copperlist_bytes: 0,
        }
    }

    pub fn reader(&self, path: &Path) -> CuResult<RunReader> {
        let mut inner = build_read_logger(path)?;
        inner.seek(self.start)?;
        let remaining = inner.raw_main_header().sections_end / 512 + 1;
        Ok(RunReader {
            inner,
            run_id: self.run_id,
            remaining,
        })
    }
}

/// Discover constructions from section identities, including runs whose startup rolled out.
pub(crate) fn discover(path: &Path) -> CuResult<Vec<RecordedRun>> {
    let mut reader = build_read_logger(path)?;
    let metadata = reader.application_metadata()?;
    let beginning = reader.position();
    let mut runs = Vec::<RecordedRun>::new();
    let mut remaining = reader.raw_main_header().sections_end / 512 + 1;
    loop {
        remaining = remaining
            .checked_sub(1)
            .ok_or_else(|| CuError::from("Cyclic section links"))?;
        let position = reader.position();
        let header = reader.raw_skip_section()?;
        let content = if header.entry_type == UnifiedLogType::RuntimeLifecycle {
            reader.seek(position)?;
            reader.raw_read_section()?.1
        } else {
            Vec::new()
        };
        if header.entry_type == UnifiedLogType::LastEntry {
            break;
        }
        if matches!(
            header.entry_type,
            UnifiedLogType::ApplicationMetadata | UnifiedLogType::ValueDecodeCatalog
        ) {
            continue;
        }
        let run_id = header.context.run_id;
        let index = if let Some(index) = runs.iter().position(|run| run.run_id == run_id) {
            index
        } else {
            let mut run = RecordedRun::new(runs.len(), beginning);
            run.run_id = run_id;
            run.mission_index = header.context.mission_index;
            if let Some(metadata) = &metadata {
                run.config = Some(metadata.effective_config_ron.clone());
                run.stack = Some(RuntimeLifecycleStackInfo {
                    app_name: metadata.app_name.clone(),
                    app_version: metadata.app_version.clone(),
                    git_commit: metadata.git_commit.clone(),
                    git_dirty: metadata.git_dirty,
                    subsystem_id: metadata.subsystem_id.clone(),
                    subsystem_code: metadata.subsystem_code,
                    instance_id: header.context.instance_id,
                });
            }
            runs.push(run);
            runs.len() - 1
        };
        let run = &mut runs[index];
        if let Some(metadata) = &metadata {
            if run.run_id != 0 && run.mission_index != header.context.mission_index {
                return Err(CuError::from(
                    "Run contains inconsistent mission identities",
                ));
            }
            let mission = metadata
                .missions
                .get(header.context.mission_index as usize)
                .ok_or(CuError::from(
                    "Section mission index is outside static metadata",
                ))?;
            if !run.missions.contains(mission) {
                run.missions.push(mission.clone());
            }
            if run
                .stack
                .as_ref()
                .is_some_and(|stack| stack.instance_id != header.context.instance_id)
            {
                return Err(CuError::from(
                    "Run contains inconsistent instance identities",
                ));
            }
        }
        if header.entry_type == UnifiedLogType::CopperList {
            run.copperlist_bytes += header.used as u64;
        }
        if header.entry_type == UnifiedLogType::RuntimeLifecycle {
            let mut remaining = content.as_slice();
            while !remaining.is_empty() {
                let (record, used) =
                    decode_from_slice::<RuntimeLifecycleRecord, _>(remaining, standard()).map_err(
                        |e| CuError::new_with_cause("Invalid runtime lifecycle record", e),
                    )?;
                match record.event {
                    RuntimeLifecycleEvent::Instantiated { .. } => {
                        run.started_at = Some(record.timestamp);
                    }
                    RuntimeLifecycleEvent::ShutdownCompleted => {
                        run.shutdown_completed = true;
                    }
                    _ => {}
                }
                remaining = &remaining[used..];
            }
        }
        if reader.position() == position {
            return Err(CuError::from("Section traversal did not advance"));
        }
    }
    if runs.is_empty() {
        let mut run = RecordedRun::new(0, beginning);
        if let Some(metadata) = metadata {
            run.config = Some(metadata.effective_config_ron);
            run.missions.extend(metadata.missions.into_iter().take(1));
        }
        runs.push(run);
    }
    Ok(runs)
}

pub(crate) fn select(runs: &[RecordedRun], requested: Option<usize>) -> CuResult<&RecordedRun> {
    let index = match requested {
        Some(index) => index,
        None if runs.len() == 1 => 0,
        None => {
            return Err(CuError::from(format!(
                "Log contains {} recorded runs; use list-runs and select --run <index>",
                runs.len()
            )));
        }
    };
    let run = runs.get(index).ok_or_else(|| {
        CuError::from(format!(
            "Recorded run {index} does not exist; use list-runs to see available runs"
        ))
    })?;
    Ok(run)
}

pub(crate) struct RunReader {
    inner: UnifiedLoggerRead,
    run_id: u64,
    remaining: u64,
}

impl RunReader {
    pub(crate) fn position(&self) -> LogPosition {
        self.inner.position()
    }
    pub fn raw_main_header(&self) -> &MainHeader {
        self.inner.raw_main_header()
    }

    fn visit(&mut self) -> CuResult<()> {
        self.remaining = self
            .remaining
            .checked_sub(1)
            .ok_or_else(|| CuError::from("Cyclic section links"))?;
        Ok(())
    }
    #[cfg(feature = "self-describing-logs")]
    pub fn read_next_section_type_at(
        &mut self,
        kind: UnifiedLogType,
    ) -> CuResult<Option<(LogPosition, Vec<u8>)>> {
        loop {
            let position = self.position();
            self.visit()?;
            let header = self.inner.raw_skip_section()?;
            if header.entry_type == UnifiedLogType::LastEntry {
                return Ok(None);
            }
            if header.entry_type == kind
                && (header.context.run_id == self.run_id
                    || matches!(
                        kind,
                        UnifiedLogType::ApplicationMetadata | UnifiedLogType::ValueDecodeCatalog
                    ))
            {
                if kind == UnifiedLogType::ValueDecodeCatalog
                    && header.used as usize > 16 * 1024 * 1024 * 9 / 8 + 8
                {
                    return Err("Catalog exceeds offline size limit".into());
                }
                self.inner.seek(position)?;
                return self
                    .inner
                    .raw_read_section()
                    .map(|(_, bytes)| Some((position, bytes)));
            }
        }
    }

    pub fn raw_read_section(&mut self) -> CuResult<(SectionHeader, Vec<u8>)> {
        loop {
            self.visit()?;
            let (header, content) = self.inner.raw_read_section()?;
            if header.entry_type == UnifiedLogType::LastEntry
                || header.context.run_id == self.run_id
                || matches!(
                    header.entry_type,
                    UnifiedLogType::ApplicationMetadata | UnifiedLogType::ValueDecodeCatalog
                )
            {
                return Ok((header, content));
            }
        }
    }

    fn read_next_section_type(&mut self, kind: UnifiedLogType) -> CuResult<Option<Vec<u8>>> {
        loop {
            let (header, content) = self.raw_read_section()?;
            if header.entry_type == UnifiedLogType::LastEntry {
                return Ok(None);
            }
            if header.entry_type == kind {
                return Ok(Some(content));
            }
        }
    }

    pub fn stream(self, kind: UnifiedLogType) -> RunStream {
        RunStream {
            reader: self,
            kind,
            buffer: Vec::new(),
            offset: 0,
            finished: false,
        }
    }
}

pub(crate) struct RunStream {
    reader: RunReader,
    kind: UnifiedLogType,
    buffer: Vec<u8>,
    offset: usize,
    finished: bool,
}

impl Read for RunStream {
    fn read(&mut self, destination: &mut [u8]) -> io::Result<usize> {
        if destination.is_empty() || self.finished {
            return Ok(0);
        }
        while self.offset == self.buffer.len() {
            let content = self
                .reader
                .read_next_section_type(self.kind)
                .map_err(|e| io::Error::other(e.to_string()))?;
            let Some(content) = content else {
                self.finished = true;
                return Ok(0);
            };
            self.buffer = content;
            self.offset = 0;
        }
        let count = destination.len().min(self.buffer.len() - self.offset);
        destination[..count].copy_from_slice(&self.buffer[self.offset..self.offset + count]);
        self.offset += count;
        Ok(count)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cu29::prelude::*;
    use std::sync::{Arc, Mutex};
    fn metadata() -> ApplicationMetadata {
        ApplicationMetadata {
            app_type: "App".into(),
            app_name: "test".into(),
            app_version: "1".into(),
            git_commit: None,
            git_dirty: None,
            subsystem_id: None,
            subsystem_code: 0,
            effective_config_ron: "(tasks:[])".into(),
            missions: vec!["alpha".into(), "beta".into()],
            catalog_offset: 0,
        }
    }
    fn directory() -> tempfile::TempDir {
        let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/export-tests");
        std::fs::create_dir_all(&path).unwrap();
        tempfile::TempDir::new_in(path).unwrap()
    }
    #[test]
    fn interleaved_and_cropped_runs_use_section_context_and_shared_metadata() {
        let dir = directory();
        let path = dir.path().join("runs.copper");
        let UnifiedLogger::Write(mut logger) = UnifiedLoggerBuilder::new()
            .file_base_name(&path)
            .preallocated_size(4096)
            .rollover(16384)
            .write(true)
            .create(true)
            .build()
            .unwrap()
        else {
            unreachable!()
        };
        logger
            .seal_metadata(&metadata(), Some(&[1u8; 100]))
            .unwrap();
        let first = logger.construction_context(7, 0).unwrap();
        let second = logger.construction_context(9, 1).unwrap();
        let logger = Arc::new(Mutex::new(logger));
        for context in [first, second] {
            let mut stream =
                stream_write_context::<RuntimeLifecycleRecord, memmap::MmapSectionStorage>(
                    logger.clone(),
                    UnifiedLogType::RuntimeLifecycle,
                    1024,
                    context,
                )
                .unwrap();
            stream
                .log(&RuntimeLifecycleRecord {
                    timestamp: CuTime::from_nanos(100),
                    event: RuntimeLifecycleEvent::Instantiated {
                        config_source: RuntimeLifecycleConfigSource::ExternalFile,
                    },
                })
                .unwrap();
        }
        for value in 0..60u32 {
            let context = if value.is_multiple_of(2) {
                first
            } else {
                second
            };
            let mut stream = stream_write_context::<u32, memmap::MmapSectionStorage>(
                logger.clone(),
                UnifiedLogType::CopperList,
                1024,
                context,
            )
            .unwrap();
            stream.log(&value).unwrap();
        }
        drop(logger);
        let runs = discover(&path).unwrap();
        assert_eq!(runs.len(), 2);
        assert!(select(&runs, None).is_err());
        for run in &runs {
            assert!(run.started_at.is_none());
            assert!(!run.shutdown_completed);
            assert_eq!(run.config.as_deref(), Some("(tasks:[])"));
            let context = if run.run_id == first.run_id {
                first
            } else {
                second
            };
            assert_eq!(run.stack.as_ref().unwrap().instance_id, context.instance_id);
            assert_eq!(
                run.missions,
                [if context.mission_index == 0 {
                    "alpha"
                } else {
                    "beta"
                }]
            );
            let mut bytes = Vec::new();
            run.reader(&path)
                .unwrap()
                .stream(UnifiedLogType::CopperList)
                .read_to_end(&mut bytes)
                .unwrap();
            assert!(
                bytes.iter().all(
                    |value| u32::from(*value).is_multiple_of(2) == (context.mission_index == 0)
                )
            );
            assert!(!bytes.is_empty());
            let mut catalog = Vec::new();
            run.reader(&path)
                .unwrap()
                .stream(UnifiedLogType::ValueDecodeCatalog)
                .read_to_end(&mut catalog)
                .unwrap();
            assert_eq!(catalog.len(), 100);
        }
    }
    #[test]
    fn standalone_writer_has_one_run_and_selection_ignores_other_run_payloads() {
        let dir = directory();
        let path = dir.path().join("standalone.copper");
        {
            let UnifiedLogger::Write(mut logger) = UnifiedLoggerBuilder::new()
                .file_base_name(&path)
                .preallocated_size(8192)
                .write(true)
                .create(true)
                .build()
                .unwrap()
            else {
                unreachable!()
            };
            let mut handle = logger
                .add_section(UnifiedLogType::CopperList, 1024)
                .unwrap();
            handle.append(42u32).unwrap();
            logger.flush_section(&mut handle);
        }
        let runs = discover(&path).unwrap();
        assert_eq!(runs.len(), 1);
        assert!(runs[0].stack.is_none());
        let mut bytes = Vec::new();
        select(&runs, None)
            .unwrap()
            .reader(&path)
            .unwrap()
            .stream(UnifiedLogType::CopperList)
            .read_to_end(&mut bytes)
            .unwrap();
        assert_eq!(bytes, [42]);
    }
}