Skip to main content

cu29_unifiedlog/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2
3extern crate alloc;
4extern crate core;
5
6#[doc(hidden)]
7pub mod byte_log;
8#[cfg(feature = "std")]
9pub mod memmap;
10pub mod noop;
11
12#[cfg(feature = "std")]
13mod compat {
14    // backward compatibility for the std implementation
15    pub use crate::memmap::LogPosition;
16    pub use crate::memmap::MmapUnifiedLogger as UnifiedLogger;
17    pub use crate::memmap::MmapUnifiedLoggerBuilder as UnifiedLoggerBuilder;
18    pub use crate::memmap::MmapUnifiedLoggerRead as UnifiedLoggerRead;
19    pub use crate::memmap::MmapUnifiedLoggerWrite as UnifiedLoggerWrite;
20    pub use crate::memmap::UnifiedLoggerIOReader;
21}
22
23#[cfg(feature = "std")]
24pub use compat::*;
25pub use noop::{NoopLogger, NoopSectionStorage};
26
27use alloc::string::ToString;
28#[cfg(not(feature = "std"))]
29use alloc::sync::Arc;
30use alloc::vec::Vec;
31use core::fmt::{Debug, Display, Formatter, Result as FmtResult};
32#[cfg(not(feature = "std"))]
33use spin::Mutex;
34#[cfg(feature = "std")]
35use std::sync::{Arc, Mutex};
36
37use bincode::error::EncodeError;
38use bincode::{Decode, Encode};
39use cu29_traits::{CuError, CuResult, UnifiedLogType, WriteStream};
40
41/// ID to spot the beginning of a Copper Log
42#[allow(dead_code)]
43pub const MAIN_MAGIC: [u8; 4] = [0xB4, 0xA5, 0x50, 0xFF]; // BRASS OFF
44
45/// ID to spot a section of Copper Log
46pub const SECTION_MAGIC: [u8; 2] = [0xFA, 0x57]; // FAST
47
48/// Version of the unified log **encapsulation only**: file headers, section
49/// headers, and the layout used to locate sections in a slab.
50///
51/// This is **never** a version of the encoded content inside sections. Changes
52/// to CopperLists, payload types, keyframes, or their serialization must not bump
53/// this value. Decode content with the logreader built for the exact application
54/// version that produced it; this header cannot establish content compatibility.
55/// Unreleased version 2 uses byte links, static metadata and construction contexts.
56pub const UNIFIED_LOG_FORMAT_VERSION: u8 = 2;
57
58pub const SECTION_HEADER_COMPACT_SIZE: u16 = 512; // Usual minimum size for a disk sector.
59
60/// Header of the byte-addressed log. All offsets are relative to the log origin.
61#[derive(Encode, Decode, Debug, Clone)]
62pub struct MainHeader {
63    pub magic: [u8; 4],
64    pub format_version: u8,
65    pub page_size: u16,
66    pub metadata_offset: u64,
67    pub sections_begin: u64,
68    pub sections_end: u64,
69    pub head_section: u64,
70    pub tail_section: u64,
71    pub clean_close: bool,
72}
73
74impl Display for MainHeader {
75    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
76        write!(
77            f,
78            "  format_version -> {}\n  alignment -> {}\n  metadata -> {}\n  data -> {}..{}\n  head -> {}\n  tail -> {}\n  clean_close -> {}",
79            self.format_version,
80            self.page_size,
81            self.metadata_offset,
82            self.sections_begin,
83            self.sections_end,
84            self.head_section,
85            self.tail_section,
86            self.clean_close
87        )
88    }
89}
90
91/// Construction identity shared by every section of an application instance.
92#[derive(Encode, Decode, Debug, Clone, Copy, Default, PartialEq, Eq)]
93pub struct SectionContext {
94    pub run_id: u64,
95    pub instance_id: u32,
96    pub mission_index: u32,
97}
98
99/// One linked section. The allocation includes its 512-byte header reservation.
100#[derive(Encode, Decode, Debug, Clone)]
101pub struct SectionHeader {
102    pub magic: [u8; 2],
103    pub block_size: u16,
104    pub entry_type: UnifiedLogType,
105    pub allocated: u64,
106    pub next_section: u64,
107    pub used: u32,
108    pub is_open: bool,
109    pub context: SectionContext,
110}
111
112impl Display for SectionHeader {
113    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
114        write!(
115            f,
116            "    type -> {:?}\n    use -> {} / {} (open: {})\n    next -> {}\n    context -> {:?}",
117            self.entry_type,
118            self.used,
119            self.allocated,
120            self.is_open,
121            self.next_section,
122            self.context
123        )
124    }
125}
126
127impl Default for SectionHeader {
128    fn default() -> Self {
129        Self {
130            magic: SECTION_MAGIC,
131            block_size: SECTION_HEADER_COMPACT_SIZE,
132            entry_type: UnifiedLogType::Empty,
133            allocated: 0,
134            next_section: 0,
135            used: 0,
136            is_open: true,
137            context: SectionContext::default(),
138        }
139    }
140}
141
142/// Static application identity and configuration, retained outside the data ring.
143#[derive(Encode, Decode, Debug, Clone, PartialEq, Eq)]
144pub struct ApplicationMetadata {
145    pub app_type: alloc::string::String,
146    pub app_name: alloc::string::String,
147    pub app_version: alloc::string::String,
148    pub git_commit: Option<alloc::string::String>,
149    pub git_dirty: Option<bool>,
150    pub subsystem_id: Option<alloc::string::String>,
151    pub subsystem_code: u16,
152    pub effective_config_ron: alloc::string::String,
153    pub missions: Vec<alloc::string::String>,
154    pub catalog_offset: u64,
155}
156
157/// Behavior when a section needs additional storage.
158#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
159pub enum CapacityPolicy {
160    #[default]
161    Grow,
162    OverwriteOldest,
163    StopWhenFull,
164}
165
166pub enum AllocatedSection<S: SectionStorage> {
167    NoMoreSpace,
168    Section(SectionHandle<S>),
169}
170
171/// Internal append outcome; rebinding happens before any entry bytes are written.
172#[doc(hidden)]
173pub enum SectionAppendOutcome {
174    Appended(usize),
175    Rebind,
176}
177
178/// A Storage is an append-only structure that can update a header section.
179pub trait SectionStorage: Send + Sync {
180    /// This rewinds the storage, serialize the header and jumps to the beginning of the user data storage.
181    fn initialize<E: Encode>(&mut self, header: &E) -> Result<usize, EncodeError>;
182    /// This updates the header leaving the position to the end of the user data storage.
183    fn post_update_header<E: Encode>(&mut self, header: &E) -> Result<usize, EncodeError>;
184    /// Appends the entry to the user data storage.
185    fn append<E: Encode>(&mut self, entry: &E) -> Result<usize, EncodeError>;
186    /// Acquire and append, distinguishing revoked access from encoding failure.
187    /// Reclaimable storage overrides this with one authoritative acquisition.
188    #[doc(hidden)]
189    fn append_or_rebind<E: Encode>(
190        &mut self,
191        entry: &E,
192    ) -> Result<SectionAppendOutcome, EncodeError> {
193        if self.is_sealed() {
194            Ok(SectionAppendOutcome::Rebind)
195        } else {
196            self.append(entry).map(SectionAppendOutcome::Appended)
197        }
198    }
199    /// Whether this handle was sealed by section reclamation.
200    fn is_sealed(&self) -> bool {
201        false
202    }
203    /// Flushes the section to the underlying storage
204    fn flush(&mut self) -> CuResult<usize>;
205}
206
207/// A SectionHandle is a handle to a section in the datalogger.
208/// It allows tracking the lifecycle of the section.
209#[derive(Default)]
210pub struct SectionHandle<S: SectionStorage> {
211    header: SectionHeader, // keep a copy of the header as metadata
212    storage: S,
213}
214
215impl<S: SectionStorage> SectionHandle<S> {
216    pub fn create(header: SectionHeader, mut storage: S) -> CuResult<Self> {
217        // Write the first version of the header.
218        let _ = storage.initialize(&header).map_err(|e| e.to_string())?;
219        Ok(Self { header, storage })
220    }
221
222    pub fn mark_closed(&mut self) {
223        self.header.is_open = false;
224    }
225    pub fn append<E: Encode>(&mut self, entry: E) -> Result<usize, EncodeError> {
226        self.storage.append(&entry)
227    }
228
229    pub fn get_storage(&self) -> &S {
230        &self.storage
231    }
232
233    pub fn get_storage_mut(&mut self) -> &mut S {
234        &mut self.storage
235    }
236
237    pub fn post_update_header(&mut self) -> Result<usize, EncodeError> {
238        self.storage.post_update_header(&self.header)
239    }
240}
241
242/// Basic statistics for the unified logger.
243/// Note: the total_allocated_space might grow for the std implementation
244pub struct UnifiedLogStatus {
245    /// Bytes reserved for headers, static metadata and retained data sections.
246    pub total_used_space: usize,
247    /// Total logical backing capacity, including free space.
248    pub total_allocated_space: usize,
249}
250
251/// Payload stored in the end-of-log section to signal whether the log was cleanly closed.
252#[derive(Encode, Decode, Debug, Clone)]
253pub struct EndOfLogMarker {
254    pub temporary: bool,
255}
256
257/// The writing interface to the unified logger.
258/// Writing is "almost" linear as various streams can allocate sections and track them until
259/// they drop them.
260pub trait UnifiedLogWrite<S: SectionStorage>: Send + Sync {
261    /// A section is a contiguous chunk of memory that can be used to write data.
262    /// It can store various types of data as specified by the entry_type.
263    /// The requested_section_size is the size of the section to allocate.
264    /// It returns a handle to the section that can be used to write data until
265    /// it is flushed with flush_section, it is then considered unmutable.
266    fn add_section(
267        &mut self,
268        entry_type: UnifiedLogType,
269        requested_section_size: usize,
270    ) -> CuResult<SectionHandle<S>>;
271
272    /// Flush the given section to the underlying storage.
273    fn flush_section(&mut self, section: &mut SectionHandle<S>);
274
275    /// Flush a section, reporting storage failures.
276    fn try_flush_section(&mut self, section: &mut SectionHandle<S>) -> CuResult<()> {
277        self.flush_section(section);
278        Ok(())
279    }
280
281    /// Seal or compare static metadata before initializing runtime streams.
282    #[doc(hidden)]
283    fn seal_metadata<C: Encode>(
284        &mut self,
285        _metadata: &ApplicationMetadata,
286        _catalog: Option<&C>,
287    ) -> CuResult<()> {
288        Err(CuError::from(
289            "Logger does not support application metadata",
290        ))
291    }
292    /// Reserve a construction identity after static metadata has been compared.
293    #[doc(hidden)]
294    fn construction_context(
295        &mut self,
296        instance_id: u32,
297        mission_index: u32,
298    ) -> CuResult<SectionContext> {
299        Ok(SectionContext {
300            run_id: 0,
301            instance_id,
302            mission_index,
303        })
304    }
305    /// Allocate a section belonging to one construction.
306    #[doc(hidden)]
307    fn add_section_with_context(
308        &mut self,
309        kind: UnifiedLogType,
310        size: usize,
311        _context: SectionContext,
312    ) -> CuResult<SectionHandle<S>> {
313        self.add_section(kind, size)
314    }
315    /// Returns the current status of the unified logger.
316    fn status(&self) -> UnifiedLogStatus;
317}
318
319/// Read back a unified log linearly.
320pub trait UnifiedLogRead {
321    /// Read through the unified logger until it reaches the UnifiedLogType given in datalogtype.
322    /// It will return the byte array of the section if found.
323    fn read_next_section_type(&mut self, datalogtype: UnifiedLogType) -> CuResult<Option<Vec<u8>>>;
324
325    /// Read through the next section entry regardless of its type.
326    /// It will return the header and the byte array of the section.
327    /// Note the last Entry should be of UnifiedLogType::LastEntry if the log is not corrupted.
328    fn raw_read_section(&mut self) -> CuResult<(SectionHeader, Vec<u8>)>;
329}
330
331/// Create a new stream to write to the unifiedlogger.
332pub fn stream_write<E: Encode, S: SectionStorage>(
333    logger: Arc<Mutex<impl UnifiedLogWrite<S>>>,
334    entry_type: UnifiedLogType,
335    minimum_allocation_amount: usize,
336) -> CuResult<impl WriteStream<E>> {
337    LogStream::new(entry_type, logger, minimum_allocation_amount)
338}
339
340/// Create a stream whose sections retain their construction identity across rollover.
341#[doc(hidden)]
342pub fn stream_write_context<E: Encode, S: SectionStorage>(
343    logger: Arc<Mutex<impl UnifiedLogWrite<S>>>,
344    entry_type: UnifiedLogType,
345    size: usize,
346    context: SectionContext,
347) -> CuResult<impl WriteStream<E>> {
348    LogStream::with_context(entry_type, logger, size, context)
349}
350
351/// A wrapper around the unifiedlogger that implements the Write trait.
352pub struct LogStream<S: SectionStorage, L: UnifiedLogWrite<S>> {
353    entry_type: UnifiedLogType,
354    parent_logger: Arc<Mutex<L>>,
355    current_section: SectionHandle<S>,
356    minimum_allocation_amount: usize,
357    last_log_bytes: usize,
358    context: SectionContext,
359}
360
361// Storage has already appended: detect invalid accounting without publishing
362// a truncated/wrapped header. This cannot roll back a faulty storage writer.
363fn record_bytes(header: &mut SectionHeader, bytes: usize) -> CuResult<()> {
364    let bytes = u32::try_from(bytes)
365        .map_err(|_| CuError::from("Encoded entry size exceeds section counter"))?;
366    header.used = header
367        .used
368        .checked_add(bytes)
369        .ok_or_else(|| CuError::from("Encoded section size exceeds section counter"))?;
370    Ok(())
371}
372
373impl<S: SectionStorage, L: UnifiedLogWrite<S>> LogStream<S, L> {
374    /// Creates a concrete stream, including for borrowed canonical encoded entries.
375    pub fn new(
376        entry_type: UnifiedLogType,
377        parent_logger: Arc<Mutex<L>>,
378        minimum_allocation_amount: usize,
379    ) -> CuResult<Self> {
380        Self::with_context(
381            entry_type,
382            parent_logger,
383            minimum_allocation_amount,
384            SectionContext::default(),
385        )
386    }
387
388    #[doc(hidden)]
389    pub fn with_context(
390        entry_type: UnifiedLogType,
391        parent_logger: Arc<Mutex<L>>,
392        minimum_allocation_amount: usize,
393        context: SectionContext,
394    ) -> CuResult<Self> {
395        #[cfg(feature = "std")]
396        let section = parent_logger
397            .lock()
398            .map_err(|e| {
399                CuError::from("Could not lock a section at LogStream creation")
400                    .add_cause(e.to_string().as_str())
401            })?
402            .add_section_with_context(entry_type, minimum_allocation_amount, context)?;
403
404        #[cfg(not(feature = "std"))]
405        let section = parent_logger.lock().add_section_with_context(
406            entry_type,
407            minimum_allocation_amount,
408            context,
409        )?;
410
411        Ok(Self {
412            entry_type,
413            parent_logger,
414            current_section: section,
415            minimum_allocation_amount,
416            last_log_bytes: 0,
417            context,
418        })
419    }
420}
421
422impl<S: SectionStorage, L: UnifiedLogWrite<S>> Debug for LogStream<S, L> {
423    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
424        write!(
425            f,
426            "MmapStream {{ entry_type: {:?}, current_position: {}, minimum_allocation_amount: {} }}",
427            self.entry_type, self.current_section.header.used, self.minimum_allocation_amount
428        )
429    }
430}
431
432impl<E: Encode, S: SectionStorage, L: UnifiedLogWrite<S>> WriteStream<E> for LogStream<S, L> {
433    fn log(&mut self, obj: &E) -> CuResult<()> {
434        let result = self.current_section.storage.append_or_rebind(obj);
435        let rebind = matches!(&result, Ok(SectionAppendOutcome::Rebind));
436        match result {
437            Ok(SectionAppendOutcome::Appended(nb_bytes)) => {
438                record_bytes(&mut self.current_section.header, nb_bytes)?;
439                self.last_log_bytes = nb_bytes;
440                // Lifecycle sections are promptly closed, so sparse events cannot pin the ring.
441                if self.entry_type == UnifiedLogType::RuntimeLifecycle {
442                    self.current_section.storage.flush()?;
443                }
444                Ok(())
445            }
446            Ok(SectionAppendOutcome::Rebind) | Err(EncodeError::UnexpectedEnd) => {
447                if !rebind && self.current_section.header.used == 0 {
448                    return Err(CuError::from("Entry exceeds an empty section"));
449                }
450                #[cfg(feature = "std")]
451                let logger_guard = self.parent_logger.lock();
452
453                #[cfg(not(feature = "std"))]
454                let mut logger_guard = self.parent_logger.lock();
455
456                #[cfg(feature = "std")]
457                let mut logger_guard = match logger_guard {
458                    Ok(g) => g,
459                    Err(_) => {
460                        return Err(
461                            "Logger mutex poisoned while reporting EncodeError::UnexpectedEnd"
462                                .into(),
463                        );
464                    } // It will retry but at least not completely crash.
465                };
466
467                logger_guard.try_flush_section(&mut self.current_section)?;
468                self.current_section = logger_guard.add_section_with_context(
469                    self.entry_type,
470                    self.minimum_allocation_amount,
471                    self.context,
472                )?;
473
474                let result = self.current_section.append(obj).map_err(|e| {
475                    CuError::from(
476                        "Failed to encode object in a newly minted section. Unrecoverable failure.",
477                    )
478                    .add_cause(e.to_string().as_str())
479                })?; // If we fail just after creating a section, there is not much we can do.
480
481                record_bytes(&mut self.current_section.header, result)?;
482                self.last_log_bytes = result;
483                if self.entry_type == UnifiedLogType::RuntimeLifecycle {
484                    self.current_section.storage.flush()?;
485                }
486                Ok(())
487            }
488            Err(e) => {
489                let err = <&str as Into<CuError>>::into("Unexpected error while encoding object.")
490                    .add_cause(e.to_string().as_str());
491                Err(err)
492            }
493        }
494    }
495
496    fn flush(&mut self) -> CuResult<()> {
497        #[cfg(feature = "std")]
498        let mut logger = self
499            .parent_logger
500            .lock()
501            .map_err(|_| CuError::from("Logger mutex poisoned"))?;
502        #[cfg(not(feature = "std"))]
503        let mut logger = self.parent_logger.lock();
504        logger.try_flush_section(&mut self.current_section)
505    }
506
507    fn last_log_bytes(&self) -> Option<usize> {
508        Some(self.last_log_bytes)
509    }
510}
511
512impl<S: SectionStorage, L: UnifiedLogWrite<S>> Drop for LogStream<S, L> {
513    fn drop(&mut self) {
514        #[cfg(feature = "std")]
515        match self.parent_logger.lock() {
516            Ok(mut logger_guard) => {
517                logger_guard.flush_section(&mut self.current_section);
518            }
519            Err(_) => {
520                // Only surface the warning when a real poisoning occurred.
521                if !std::thread::panicking() {
522                    eprintln!("⚠️ MmapStream::drop: logger mutex poisoned");
523                }
524            }
525        }
526
527        #[cfg(not(feature = "std"))]
528        {
529            let mut logger_guard = self.parent_logger.lock();
530            logger_guard.flush_section(&mut self.current_section);
531        }
532    }
533}
534
535#[cfg(test)]
536mod accounting_tests {
537    use super::*;
538
539    // A deliberately faulty storage backend reports sizes without encoding data.
540    struct ReportedSizeStorage {
541        bytes: usize,
542        rebind: bool,
543    }
544    impl SectionStorage for ReportedSizeStorage {
545        fn initialize<E: Encode>(&mut self, _: &E) -> Result<usize, EncodeError> {
546            Ok(0)
547        }
548        fn post_update_header<E: Encode>(&mut self, _: &E) -> Result<usize, EncodeError> {
549            Ok(0)
550        }
551        fn append<E: Encode>(&mut self, _: &E) -> Result<usize, EncodeError> {
552            Ok(self.bytes)
553        }
554        fn append_or_rebind<E: Encode>(
555            &mut self,
556            entry: &E,
557        ) -> Result<SectionAppendOutcome, EncodeError> {
558            if self.rebind {
559                Ok(SectionAppendOutcome::Rebind)
560            } else {
561                self.append(entry).map(SectionAppendOutcome::Appended)
562            }
563        }
564        fn flush(&mut self) -> CuResult<usize> {
565            Ok(0)
566        }
567    }
568    struct ReportedSizeLogger {
569        bytes: usize,
570        rebind: bool,
571    }
572    impl UnifiedLogWrite<ReportedSizeStorage> for ReportedSizeLogger {
573        fn add_section(
574            &mut self,
575            _: UnifiedLogType,
576            _: usize,
577        ) -> CuResult<SectionHandle<ReportedSizeStorage>> {
578            SectionHandle::create(
579                SectionHeader::default(),
580                ReportedSizeStorage {
581                    bytes: self.bytes,
582                    rebind: self.rebind,
583                },
584            )
585        }
586        fn flush_section(&mut self, _: &mut SectionHandle<ReportedSizeStorage>) {}
587        fn status(&self) -> UnifiedLogStatus {
588            UnifiedLogStatus {
589                total_used_space: 0,
590                total_allocated_space: 0,
591            }
592        }
593    }
594
595    #[test]
596    fn test_stream_rejects_counter_overflow_without_changing_header() {
597        let logger = Arc::new(Mutex::new(ReportedSizeLogger {
598            bytes: u32::MAX as usize,
599            rebind: false,
600        }));
601        let mut stream = LogStream::new(UnifiedLogType::CopperList, logger, 4096).unwrap();
602        stream.log(&0_u8).unwrap();
603        assert!(stream.log(&0_u8).is_err());
604        assert_eq!(stream.current_section.header.used, u32::MAX);
605    }
606
607    #[test]
608    #[cfg(target_pointer_width = "64")]
609    fn test_stream_rejects_truncation_on_append_and_rebind() {
610        for rebind in [false, true] {
611            let logger = Arc::new(Mutex::new(ReportedSizeLogger {
612                bytes: u32::MAX as usize + 1,
613                rebind,
614            }));
615            let mut stream = LogStream::new(UnifiedLogType::CopperList, logger, 4096).unwrap();
616            assert!(stream.log(&0_u8).is_err());
617            assert_eq!(stream.current_section.header.used, 0);
618            assert_eq!(WriteStream::<u8>::last_log_bytes(&stream), Some(0));
619        }
620    }
621}