Skip to main content

link_cli/engine/partitioned/
chunks.rs

1//! Versioned chunk manifests. Write limits are selected independently of caching.
2use super::{error, LinkError};
3
4/// Optional immutable chunk layout; whole-journal objects remain the default.
5#[derive(Debug, Clone, Copy)]
6pub struct JournalChunkOptions {
7    pub max_records: usize,
8    pub max_bytes: usize,
9    pub max_chunks: usize,
10}
11impl Default for JournalChunkOptions {
12    fn default() -> Self {
13        Self {
14            max_records: 64,
15            max_bytes: 65536,
16            max_chunks: 1024,
17        }
18    }
19}
20impl JournalChunkOptions {
21    pub(crate) fn validate(self) -> Result<Self, LinkError> {
22        if self.max_records == 0
23            || self.max_records > 65536
24            || self.max_bytes == 0
25            || self.max_bytes > 8388608
26            || self.max_chunks == 0
27            || self.max_chunks > 4096
28        {
29            return Err(error("invalid journal chunk limits"));
30        }
31        Ok(self)
32    }
33    pub(crate) fn split<'a>(&self, records: &'a [String]) -> Result<Vec<&'a [String]>, LinkError> {
34        let mut chunks = Vec::new();
35        let (mut start, mut bytes) = (0, 0);
36        for (index, record) in records.iter().enumerate() {
37            if record.len() > self.max_bytes {
38                return Err(error("chunk record exceeds byte limit"));
39            }
40            if index > start
41                && (index - start == self.max_records || record.len() > self.max_bytes - bytes)
42            {
43                chunks.push(&records[start..index]);
44                start = index;
45                bytes = 0;
46            }
47            if chunks.len() >= self.max_chunks {
48                return Err(error("journal chunk count limit"));
49            }
50            bytes += record.len();
51        }
52        if start < records.len() {
53            chunks.push(&records[start..]);
54        }
55        Ok(chunks)
56    }
57}
58pub(super) struct Reference {
59    pub key: String,
60    pub generation: u64,
61    pub records: Option<usize>,
62}
63pub(super) struct Manifest {
64    pub partition: String,
65    pub references: Vec<Reference>,
66}
67fn decimal(value: &str, max: u64) -> Option<u64> {
68    let number: u64 = value.parse().ok()?;
69    (number <= max && number.to_string() == value).then_some(number)
70}
71fn address(value: &str) -> bool {
72    value.len() == 22
73        && value.starts_with("blob1-")
74        && value.as_bytes()[6..]
75            .iter()
76            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(b))
77}
78pub(super) fn manifest(parts: &[String]) -> Result<Manifest, LinkError> {
79    let invalid = || error("invalid catalog pointer or chunk manifest");
80    if parts.len() == 4 && parts[0] == "blob1" && address(&parts[2]) {
81        let generation = decimal(&parts[3], u64::MAX)
82            .filter(|n| *n > 0)
83            .ok_or_else(invalid)?;
84        return Ok(Manifest {
85            partition: parts[1].clone(),
86            references: vec![Reference {
87                key: parts[2].clone(),
88                generation,
89                records: None,
90            }],
91        });
92    }
93    if parts.len() < 4 || parts[0] != "chunks1" {
94        return Err(invalid());
95    }
96    let total = decimal(&parts[2], u32::MAX.into()).ok_or_else(invalid)?;
97    let count = decimal(&parts[3], 4096).ok_or_else(invalid)? as usize;
98    if parts.len() != 4 + 3 * count {
99        return Err(invalid());
100    }
101    let mut sum = 0;
102    let mut references = Vec::with_capacity(count);
103    for triple in parts[4..].as_chunks::<3>().0 {
104        if !address(&triple[0]) {
105            return Err(invalid());
106        }
107        let generation = decimal(&triple[1], u64::MAX)
108            .filter(|n| *n > 0)
109            .ok_or_else(invalid)?;
110        let records = decimal(&triple[2], 65536)
111            .filter(|n| *n > 0)
112            .ok_or_else(invalid)?;
113        sum += records;
114        references.push(Reference {
115            key: triple[0].clone(),
116            generation,
117            records: Some(records as usize),
118        });
119    }
120    if sum != total {
121        return Err(invalid());
122    }
123    Ok(Manifest {
124        partition: parts[1].clone(),
125        references,
126    })
127}
128pub(crate) fn validate(records: &[String], count: Option<usize>) -> Result<(), LinkError> {
129    if let Some(count) = count {
130        if records.len() != count
131            || records
132                .iter()
133                .map(String::len)
134                .try_fold(0usize, |sum, n| sum.checked_add(n))
135                .is_none_or(|sum| sum > 8388608)
136        {
137            return Err(error("invalid immutable chunk count or byte bound"));
138        }
139    }
140    Ok(())
141}