Skip to main content

oxabl_cache_format/
commit_request.rs

1//! `OXCM` commit request.
2
3use crate::cursor::Cursor;
4use crate::error::{FormatError, Result};
5use crate::frame::{read_header, write_header};
6use crate::ids::{LookupId, SegmentId};
7use crate::limits::{COMMIT_ENTRIES, PACK_BYTES, PACK_SEGMENTS};
8use crate::namespace::Namespace;
9use crate::writer::{Writer, len32};
10
11const MAGIC: [u8; 4] = *b"OXCM";
12
13/// What a segment of the pack holds.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum SegmentKind {
16    Artifact,
17    Dictionary,
18}
19
20impl SegmentKind {
21    fn to_u8(self) -> u8 {
22        match self {
23            Self::Artifact => 0,
24            Self::Dictionary => 1,
25        }
26    }
27
28    fn from_u8(v: u8) -> Result<Self> {
29        match v {
30            0 => Ok(Self::Artifact),
31            1 => Ok(Self::Dictionary),
32            _ => Err(FormatError::Invalid("segment kind")),
33        }
34    }
35}
36
37/// One row of the segment table.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct CommitSegment {
40    pub segment_id: SegmentId,
41    pub offset: u64,
42    pub length: u32,
43    pub kind: SegmentKind,
44}
45
46/// One entry: a lookup id, the segment holding its artifacts and its sealed record.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct CommitEntry<'a> {
49    pub lookup_id: LookupId,
50    pub segment_idx: u32,
51    pub dict_id: Option<SegmentId>,
52    pub epoch: u32,
53    /// Sealed record bytes, opaque at this layer.
54    pub record: &'a [u8],
55}
56
57/// A commit request for one pack.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct CommitRequest<'a> {
60    pub ns: Namespace,
61    pub pack_size: u64,
62    pub segments: Vec<CommitSegment>,
63    pub entries: Vec<CommitEntry<'a>>,
64}
65
66const SEGMENT_LEN: usize = 32 + 8 + 4 + 1;
67const ENTRY_MIN: usize = 32 + 4 + 32 + 4 + 2;
68const ZERO_ID: [u8; 32] = [0; 32];
69
70impl<'a> CommitRequest<'a> {
71    pub fn encode(&self) -> Result<Vec<u8>> {
72        self.check()?;
73        let mut w = Writer::default();
74        write_header(&mut w, MAGIC, 0);
75        w.u8(self.ns.to_u8());
76        w.u8(0);
77        w.u64(self.pack_size);
78        w.u32(len32(self.segments.len(), "segments")?);
79        for s in &self.segments {
80            w.bytes(&s.segment_id.0);
81            w.u64(s.offset);
82            w.u32(s.length);
83            w.u8(s.kind.to_u8());
84        }
85        w.u32(len32(self.entries.len(), "entries")?);
86        for e in &self.entries {
87            w.bytes(&e.lookup_id.0);
88            w.u32(e.segment_idx);
89            w.bytes(&e.dict_id.map_or(ZERO_ID, |d| d.0));
90            w.u32(e.epoch);
91            w.record(e.record)?;
92        }
93        Ok(w.into_vec())
94    }
95
96    pub fn decode(bytes: &'a [u8]) -> Result<Self> {
97        let mut c = Cursor::new(bytes);
98        read_header(&mut c, MAGIC, 0)?;
99        let ns = Namespace::from_u8(c.u8()?)?;
100        c.reserved_u8()?;
101        let pack_size = c.u64()?;
102        let seg_count = c.count32(PACK_SEGMENTS, "segments", SEGMENT_LEN)?;
103        let mut segments = Vec::with_capacity(seg_count);
104        for _ in 0..seg_count {
105            segments.push(CommitSegment {
106                segment_id: SegmentId(c.array()?),
107                offset: c.u64()?,
108                length: c.u32()?,
109                kind: SegmentKind::from_u8(c.u8()?)?,
110            });
111        }
112        let entry_count = c.count32(COMMIT_ENTRIES, "entries", ENTRY_MIN)?;
113        let mut entries = Vec::with_capacity(entry_count);
114        for _ in 0..entry_count {
115            let lookup_id = LookupId(c.array()?);
116            let segment_idx = c.u32()?;
117            let dict: [u8; 32] = c.array()?;
118            entries.push(CommitEntry {
119                lookup_id,
120                segment_idx,
121                dict_id: (dict != ZERO_ID).then_some(SegmentId(dict)),
122                epoch: c.u32()?,
123                record: c.record()?,
124            });
125        }
126        c.finish()?;
127        let request = Self {
128            ns,
129            pack_size,
130            segments,
131            entries,
132        };
133        request.check()?;
134        Ok(request)
135    }
136
137    fn check(&self) -> Result<()> {
138        if self.pack_size > PACK_BYTES {
139            return Err(FormatError::LimitExceeded("pack size"));
140        }
141        if self.segments.len() > PACK_SEGMENTS {
142            return Err(FormatError::LimitExceeded("segments"));
143        }
144        if self.entries.len() > COMMIT_ENTRIES {
145            return Err(FormatError::LimitExceeded("entries"));
146        }
147        if self.ns == Namespace::Personal
148            && self
149                .segments
150                .iter()
151                .any(|s| s.kind == SegmentKind::Dictionary)
152        {
153            return Err(FormatError::Invalid(
154                "dictionary segment in a personal commit",
155            ));
156        }
157        if self
158            .entries
159            .iter()
160            .any(|e| e.dict_id.is_some_and(|d| d.0 == ZERO_ID))
161        {
162            return Err(FormatError::Invalid("zero dict_id"));
163        }
164        Ok(())
165    }
166}