Skip to main content

link_cli/engine/paged/
sorted_table.rs

1//! Sealed sorted journal records on immutable native doublets pages.
2//! Full bounded startup validation; point reads retain no payload map.
3use super::{format::*, read_committed, Cursor, PageDevice, PagedLog};
4use crate::{LinkError, TransitionLogStore};
5use serde_json::Value;
6
7const MARKER: &str = "[\"native-sst1\"]";
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct SortedJournalEntry {
10    pub key: String,
11    /// Positive, nonreused identity, retained even for a tombstone.
12    pub generation: u64,
13    pub entries: Option<Vec<String>>,
14}
15#[derive(Clone, Copy, Debug)]
16pub struct SortedTableOptions {
17    pub max_keys: usize,
18    /// Total encoded UTF-8 log record bytes, including the format marker.
19    pub max_bytes: usize,
20}
21impl Default for SortedTableOptions {
22    fn default() -> Self {
23        Self {
24            max_keys: 4096,
25            max_bytes: 8_388_608,
26        }
27    }
28}
29impl SortedTableOptions {
30    fn pages(self) -> Result<u64, LinkError> {
31        if !(1..=65_536).contains(&self.max_keys) || !(1..=67_108_864).contains(&self.max_bytes) {
32            return Err(invalid("sorted table admission bounds"));
33        }
34        Ok((self.max_bytes.div_ceil(7) as u64 + 2 * (self.max_keys as u64 + 1)).div_ceil(CELLS))
35    }
36}
37struct Index {
38    key: String,
39    generation: u64,
40    tombstone: bool,
41    root: u64,
42    previous: u64,
43}
44/// Caller owns an exclusive immutable device. Open validates the whole file;
45/// get checks selected physical pages against its retained identity/hashes.
46/// Read failure never writes, retries a mutation or changes ownership.
47pub struct SortedJournalTable<D> {
48    device: D,
49    state: Metadata,
50    index: Vec<Index>,
51    hashes: Vec<u64>,
52    stored_bytes: usize,
53}
54impl<D: PageDevice> SortedJournalTable<D> {
55    pub fn create(
56        mut device: D,
57        entries: &[SortedJournalEntry],
58        options: SortedTableOptions,
59    ) -> Result<Self, LinkError> {
60        let max_pages = options.pages()?;
61        if entries.len() > options.max_keys {
62            return Err(invalid("sorted table key limit"));
63        }
64        let mut records = vec![MARKER.to_owned()];
65        let mut bytes = MARKER.len();
66        let mut previous = "";
67        for entry in entries {
68            validate_key(&entry.key)?;
69            if entry.key.as_str() <= previous || entry.generation == 0 {
70                return Err(invalid("sorted table ordering or generation"));
71            }
72            let record =
73                serde_json::to_string(&(&entry.key, entry.generation.to_string(), &entry.entries))
74                    .map_err(|_| invalid("sorted table encoding"))?;
75            bytes += record.len();
76            if bytes > options.max_bytes {
77                return Err(invalid("sorted table byte limit"));
78            }
79            records.push(record);
80            previous = &entry.key;
81        }
82        if bytes > options.max_bytes {
83            return Err(invalid("sorted table byte limit"));
84        }
85        let raw = [device.read_metadata(0)?, device.read_metadata(1)?];
86        if raw.iter().flatten().any(|value| !value.is_empty()) || device.data_length()? != 0 {
87            return Err(invalid("sorted table creation requires an empty device"));
88        }
89        let mut log = PagedLog::with_max_pages(device, max_pages)?;
90        for record in records {
91            log.append_log_entry(&record)?;
92        }
93        log.flush_log()?;
94        Self::open(log.into_device(), options)
95    }
96    pub fn open(mut device: D, options: SortedTableOptions) -> Result<Self, LinkError> {
97        let max_pages = options.pages()?;
98        let flags = device.metadata_flags();
99        if flags > 1 {
100            return Err(invalid("unsupported sorted table device mode"));
101        }
102        let raw = [device.read_metadata(0)?, device.read_metadata(1)?];
103        let states: Vec<_> = raw
104            .iter()
105            .map(|value| Metadata::decode(value.as_deref().unwrap_or_default(), flags))
106            .collect::<Result<Vec<_>, _>>()?
107            .into_iter()
108            .flatten()
109            .collect();
110        if states.len() == 2
111            && (states[0].identity != states[1].identity
112                || (states[0].generation == states[1].generation && raw[0] != raw[1]))
113        {
114            return Err(invalid("conflicting sorted table decisions"));
115        }
116        let state = states
117            .into_iter()
118            .max_by_key(|value| value.generation)
119            .ok_or_else(|| invalid("no sealed sorted table decision"))?;
120        if state.generation != 1
121            || state.records > options.max_keys as u64 + 1
122            || state.pages > max_pages
123            || device.data_length()? != state.pages * PAGE_SIZE as u64
124        {
125            return Err(invalid("sorted table seal, length or admission bounds"));
126        }
127        let records = read_committed(&mut device, &state, true)?;
128        if records.first().map(String::as_str) != Some(MARKER) {
129            return Err(invalid("unsupported sorted table marker"));
130        }
131        let mut index = Vec::with_capacity(records.len() - 1);
132        let mut bytes = 0;
133        let mut root = 0;
134        let mut previous = "";
135        let mut previous_root = 0;
136        for (position, record) in records.iter().enumerate() {
137            bytes += record.len();
138            if bytes > options.max_bytes {
139                return Err(invalid("sorted table byte limit"));
140            }
141            root += record.len().div_ceil(7) as u64 + 1;
142            if position != 0 {
143                let entry = decode(record)?;
144                if entry.key.as_str() <= previous {
145                    return Err(invalid("sorted table key ordering"));
146                }
147                index.push(Index {
148                    key: entry.key,
149                    generation: entry.generation,
150                    tombstone: entry.entries.is_none(),
151                    root,
152                    previous: previous_root,
153                });
154                previous = &index.last().expect("inserted index").key;
155            }
156            previous_root = root;
157        }
158        // One flush fills every intermediate page, making these physical
159        // record addresses canonical. Bind the index to the validated page chain.
160        if root != state.root || root != state.rows {
161            return Err(invalid("sorted table packed addresses"));
162        }
163        let mut cursor = Cursor {
164            device: &mut device,
165            state: &state,
166            index: state.pages as i64 - 1,
167            generation: 1,
168            expected: state.last_hash,
169            page: [0; PAGE_SIZE],
170            count: 0,
171            consumed: 0,
172        };
173        let mut hashes = vec![0; state.pages as usize];
174        while cursor.index >= 0 {
175            cursor.load()?;
176            hashes[cursor.index as usize] = u64_at(&cursor.page, 56);
177            cursor.index -= 1;
178        }
179        device.complete_recovery()?;
180        Ok(Self {
181            device,
182            state,
183            index,
184            hashes,
185            stored_bytes: bytes,
186        })
187    }
188    pub fn len(&self) -> usize {
189        self.index.len()
190    }
191    pub fn is_empty(&self) -> bool {
192        self.index.is_empty()
193    }
194    pub fn stored_bytes(&self) -> usize {
195        self.stored_bytes
196    }
197    pub fn identity(&self) -> [u8; 16] {
198        self.state.identity
199    }
200    pub fn digest(&self) -> u64 {
201        self.state.last_hash
202    }
203    pub fn supports_durable_flush(&self) -> bool {
204        self.device.supports_durable_flush()
205    }
206    pub fn into_device(self) -> D {
207        self.device
208    }
209    pub fn get(&mut self, key: &str) -> Result<Option<SortedJournalEntry>, LinkError> {
210        validate_key(key)?;
211        match self
212            .index
213            .binary_search_by(|entry| entry.key.as_str().cmp(key))
214        {
215            Ok(position) => self.at(position).map(Some),
216            Err(_) => Ok(None),
217        }
218    }
219    pub fn entries(&mut self) -> Result<Vec<SortedJournalEntry>, LinkError> {
220        (0..self.index.len())
221            .map(|position| self.at(position))
222            .collect()
223    }
224    fn at(&mut self, position: usize) -> Result<SortedJournalEntry, LinkError> {
225        let entry = &self.index[position];
226        let page = (entry.root - 1) / CELLS;
227        let mut cursor = Cursor {
228            device: &mut self.device,
229            state: &self.state,
230            index: page as i64,
231            generation: 1,
232            expected: self.hashes[page as usize],
233            page: [0; PAGE_SIZE],
234            count: 0,
235            consumed: 0,
236        };
237        cursor.load()?;
238        cursor.count = ((entry.root - 1) % CELLS + 1) as usize;
239        let (source, previous) = cursor.take(entry.root)?;
240        let mut string = portable(source)?;
241        let mut bytes = Vec::new();
242        while string != 0 {
243            let (external, next) = cursor.take(string)?;
244            let length = ((external >> 56) & 7) as usize;
245            let payload = external & PAYLOAD;
246            if external & EXTERNAL == 0
247                || external & 0x7800000000000000 != 0
248                || length == 0
249                || payload >> (length * 8) != 0
250                || (next != 0 && length != 7)
251            {
252                return Err(invalid("sorted table string doublet"));
253            }
254            bytes.extend_from_slice(&payload.to_le_bytes()[..length]);
255            string = next;
256        }
257        if previous != entry.previous || cursor.current() != previous {
258            return Err(invalid("sorted table record predecessor"));
259        }
260        let record = String::from_utf8(bytes).map_err(|_| invalid("sorted table UTF-8"))?;
261        let value = decode(&record)?;
262        if value.key != entry.key
263            || value.generation != entry.generation
264            || value.entries.is_none() != entry.tombstone
265        {
266            return Err(invalid("sorted table index identity"));
267        }
268        Ok(value)
269    }
270}
271fn validate_key(key: &str) -> Result<(), LinkError> {
272    if key.is_empty()
273        || key.len() > 128
274        || !key
275            .bytes()
276            .all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b))
277    {
278        return Err(invalid("sorted table key"));
279    }
280    Ok(())
281}
282fn decode(record: &str) -> Result<SortedJournalEntry, LinkError> {
283    let value: Value =
284        serde_json::from_str(record).map_err(|_| invalid("sorted table record JSON"))?;
285    let row = value
286        .as_array()
287        .filter(|row| row.len() == 3)
288        .ok_or_else(|| invalid("sorted table record shape"))?;
289    let key = row[0]
290        .as_str()
291        .ok_or_else(|| invalid("sorted table key type"))?;
292    validate_key(key)?;
293    let text = row[1]
294        .as_str()
295        .ok_or_else(|| invalid("sorted table generation type"))?;
296    let generation = text
297        .parse::<u64>()
298        .map_err(|_| invalid("sorted table generation"))?;
299    if generation == 0 || generation.to_string() != text {
300        return Err(invalid("sorted table canonical generation"));
301    }
302    let entries = if row[2].is_null() {
303        None
304    } else {
305        Some(
306            row[2]
307                .as_array()
308                .ok_or_else(|| invalid("sorted table records"))?
309                .iter()
310                .map(|value| {
311                    value
312                        .as_str()
313                        .map(str::to_owned)
314                        .ok_or_else(|| invalid("sorted table record type"))
315                })
316                .collect::<Result<Vec<_>, _>>()?,
317        )
318    };
319    Ok(SortedJournalEntry {
320        key: key.into(),
321        generation,
322        entries,
323    })
324}