Skip to main content

aft_store/content/
sections.rs

1//! The content plane's sections in a segment.
2//!
3//! | Section | Holds |
4//! |---|---|
5//! | record units | a unit table: each record key in ascending order, located at its surface |
6//! | record surfaces | each record's surface part, uncompressed, read in place |
7//! | record bodies | each record's body part, compressed when that saves space |
8//! | body index | per unit, by ordinal: body offset (u64), stored length (u32), length when unpacked (u32), codec (u8) |
9//!
10//! Surfaces stay uncompressed because resolving any file reads the surfaces
11//! of the files it depends on, often many and often small; a body is read
12//! only when its own file is resolved.
13
14use std::collections::BTreeMap;
15use std::sync::Arc;
16
17use super::{ContentRecord, DecodeError, RecordKey, TodoMarkers};
18use crate::ids::Digest128;
19use crate::packed::{self, PackedBuilder};
20use crate::segment::{
21    Alignment, ErrorKind, KeySpace, KnownSection, Requirement, SectionHandle, SectionId,
22    SectionKind, SectionSpec, Segment, SegmentError, SegmentWriter,
23};
24use crate::table::{UnitLocation, UnitTable, UnitTableBuilder};
25
26pub(super) const UNITS: SectionKind = SectionKind::new(0x0200);
27pub(super) const SURFACES: SectionKind = SectionKind::new(0x0201);
28pub(super) const BODIES: SectionKind = SectionKind::new(0x0202);
29pub(super) const BODY_INDEX: SectionKind = SectionKind::new(0x0203);
30const VERSION: u16 = 1;
31/// The content sections' version, for a build that names what its saved
32/// work depends on.
33pub const SECTIONS_VERSION: u16 = VERSION;
34const KEY_SPACE: KeySpace = KeySpace::new(0);
35const BODY_INDEX_LEN: usize = packed::INDEX_ENTRY_LEN;
36
37/// The content sections this build reads.
38pub const KNOWN: [KnownSection; 4] = [
39    KnownSection {
40        kind: UNITS,
41        version: VERSION,
42    },
43    KnownSection {
44        kind: SURFACES,
45        version: VERSION,
46    },
47    KnownSection {
48        kind: BODIES,
49        version: VERSION,
50    },
51    KnownSection {
52        kind: BODY_INDEX,
53        version: VERSION,
54    },
55];
56
57/// A record's two parts as the sections store them, before the body is
58/// compressed.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct EncodedRecord {
61    pub surface: Vec<u8>,
62    pub body: Vec<u8>,
63}
64
65impl crate::heap::HeapBytes for EncodedRecord {
66    fn heap_bytes(&self, _seen: &mut crate::heap::Seen) -> usize {
67        self.surface.capacity() + self.body.capacity()
68    }
69}
70
71impl EncodedRecord {
72    #[must_use]
73    pub fn of(record: &ContentRecord) -> Self {
74        let (surface, body) = record.encode();
75        Self { surface, body }
76    }
77
78    /// The record again.
79    ///
80    /// # Errors
81    ///
82    /// When the bytes are not a record this build encodes.
83    pub fn decode(&self) -> Result<ContentRecord, DecodeError> {
84        ContentRecord::decode(&self.surface, &self.body)
85    }
86
87    /// The record's TODO markers, read from its surface part alone.
88    ///
89    /// # Errors
90    ///
91    /// When the surface part is not one this build encodes.
92    pub fn todos(&self) -> Result<Option<TodoMarkers>, DecodeError> {
93        ContentRecord::todos_of(&self.surface)
94    }
95}
96
97/// Collects records for the content sections of one segment.
98#[derive(Debug, Default)]
99pub struct ContentSectionsBuilder {
100    records: BTreeMap<RecordKey, Arc<EncodedRecord>>,
101}
102
103impl crate::heap::HeapBytes for ContentSectionsBuilder {
104    fn heap_bytes(&self, seen: &mut crate::heap::Seen) -> usize {
105        let entry = std::mem::size_of::<RecordKey>() + std::mem::size_of::<Arc<EncodedRecord>>();
106        crate::heap::btree_bytes(self.records.len(), entry)
107            + self
108                .records
109                .values()
110                .filter(|record| seen.first(Arc::as_ptr(record)))
111                .map(|record| {
112                    std::mem::size_of::<EncodedRecord>()
113                        + record.surface.capacity()
114                        + record.body.capacity()
115                })
116                .sum::<usize>()
117    }
118}
119
120impl ContentSectionsBuilder {
121    #[must_use]
122    pub fn new() -> Self {
123        Self::default()
124    }
125
126    /// Adds a record under `key`. Adding a key twice keeps the first.
127    pub fn add(&mut self, key: RecordKey, record: &ContentRecord) {
128        self.records
129            .entry(key)
130            .or_insert_with(|| Arc::new(EncodedRecord::of(record)));
131    }
132
133    /// Adds a record already encoded. Adding a key twice keeps the first.
134    pub fn add_encoded(&mut self, key: RecordKey, record: Arc<EncodedRecord>) {
135        self.records.entry(key).or_insert(record);
136    }
137
138    /// The encoded record under `key`, shared.
139    #[must_use]
140    pub fn get(&self, key: &RecordKey) -> Option<&Arc<EncodedRecord>> {
141        self.records.get(key)
142    }
143
144    #[must_use]
145    pub fn len(&self) -> usize {
146        self.records.len()
147    }
148
149    #[must_use]
150    pub fn is_empty(&self) -> bool {
151        self.records.is_empty()
152    }
153
154    /// Keeps only the records `keep` accepts: a build leaves out those
155    /// another segment of the family already holds.
156    pub fn retain(&mut self, mut keep: impl FnMut(RecordKey) -> bool) {
157        self.records.retain(|key, _| keep(*key));
158    }
159
160    /// Writes the four sections into `writer`.
161    ///
162    /// # Errors
163    ///
164    /// When a write fails.
165    pub fn write(self, writer: &mut SegmentWriter) -> Result<(), SegmentError> {
166        let mut table = UnitTableBuilder::new(Digest128::LEN);
167        let mut surfaces = Vec::new();
168        let mut bodies = PackedBuilder::with_capacity(self.records.len());
169        for (key, record) in self.records {
170            table.push(
171                key.digest().as_bytes(),
172                UnitLocation {
173                    offset: surfaces.len() as u64,
174                    len: u32::try_from(record.surface.len()).expect("a surface is under 4 GiB"),
175                },
176            );
177            surfaces.extend_from_slice(&record.surface);
178            bodies.push(&record.body);
179        }
180        let (bodies, index) = bodies.finish();
181        let (table, units) = table.finish();
182        writer.write_section(spec(UNITS), &table, units)?;
183        writer.write_section(spec(SURFACES), &surfaces, units)?;
184        writer.write_section(spec(BODIES), &bodies, units)?;
185        writer.write_section(spec(BODY_INDEX), &index, units)
186    }
187}
188
189/// Writes into `writer` the content sections of a segment holding `units`,
190/// each `(key, source, ordinal)` the record at `ordinal` of the source
191/// segment at `source`, copied as stored: neither part is decoded, so a
192/// record of any kind folds. The sections are the bytes a
193/// [`ContentSectionsBuilder`] holding the same records writes (see
194/// `crate::fold`). `units` must be in strictly ascending key order.
195///
196/// # Errors
197///
198/// When a read or a write fails, or a source's sections are malformed.
199///
200/// # Panics
201///
202/// When `units` is not in strictly ascending key order or names a source
203/// that is not in `sources`.
204pub fn write_folded(
205    writer: &mut SegmentWriter,
206    sources: &[ContentSegment<'_>],
207    units: &[(RecordKey, usize, u32)],
208) -> Result<(), SegmentError> {
209    // Surfaces first, so each unit's place in them is known as the table
210    // is built.
211    let mut table = UnitTableBuilder::new(Digest128::LEN);
212    let mut offset = 0u64;
213    writer.begin_section(spec(SURFACES))?;
214    for (key, source, ordinal) in units {
215        let surface = sources[*source].surface(*ordinal)?;
216        table.push(
217            key.digest().as_bytes(),
218            UnitLocation {
219                offset,
220                len: u32::try_from(surface.len()).expect("a surface is under 4 GiB"),
221            },
222        );
223        writer.write(&surface)?;
224        offset += surface.len() as u64;
225    }
226    let (table, count) = table.finish();
227    writer.end_section(count)?;
228    writer.begin_section(spec(BODIES))?;
229    let mut bodies = packed::PackedCopy::with_capacity(units.len());
230    for (_, source, ordinal) in units {
231        let source = &sources[*source];
232        let body = packed::read_stored(source.segment, source.bodies, source.index, *ordinal)?;
233        bodies.push(writer, &body)?;
234    }
235    writer.end_section(count)?;
236    writer.write_section(spec(BODY_INDEX), &bodies.finish(), count)?;
237    writer.write_section(spec(UNITS), &table, count)
238}
239
240pub(super) fn spec(kind: SectionKind) -> SectionSpec {
241    SectionSpec {
242        id: SectionId::new(kind, KEY_SPACE),
243        version: VERSION,
244        alignment: Alignment::Word,
245        requirement: Requirement::Required,
246    }
247}
248
249/// The content sections of one open segment.
250#[derive(Debug)]
251pub struct ContentSegment<'s> {
252    segment: &'s Segment,
253    units: UnitTable<'s>,
254    surfaces: SectionHandle,
255    bodies: SectionHandle,
256    index: SectionHandle,
257}
258
259impl<'s> ContentSegment<'s> {
260    /// The segment's content sections, or `None` when it has none.
261    ///
262    /// # Errors
263    ///
264    /// When the segment has only some of them, or they are malformed.
265    pub fn open(segment: &'s Segment) -> Result<Option<Self>, SegmentError> {
266        let handles = [UNITS, SURFACES, BODIES, BODY_INDEX]
267            .map(|kind| segment.section(SectionId::new(kind, KEY_SPACE)));
268        let [Some(units), Some(surfaces), Some(bodies), Some(index)] = handles else {
269            if handles.iter().any(Option::is_some) {
270                return Err(malformed(
271                    segment,
272                    "a segment has only some content sections",
273                ));
274            }
275            return Ok(None);
276        };
277        let units = UnitTable::open(segment, units)?;
278        if segment.info(index).len != u64::from(units.len()) * BODY_INDEX_LEN as u64 {
279            return Err(malformed(
280                segment,
281                "the body index does not match the unit table",
282            ));
283        }
284        Ok(Some(Self {
285            segment,
286            units,
287            surfaces,
288            bodies,
289            index,
290        }))
291    }
292
293    #[must_use]
294    pub fn len(&self) -> u32 {
295        self.units.len()
296    }
297
298    #[must_use]
299    pub fn is_empty(&self) -> bool {
300        self.units.is_empty()
301    }
302
303    /// The ordinal of the record with `key`.
304    ///
305    /// # Errors
306    ///
307    /// When a read fails.
308    pub fn find(&self, key: RecordKey) -> Result<Option<u32>, SegmentError> {
309        Ok(self
310            .units
311            .get(key.digest().as_bytes())?
312            .map(|(ordinal, _)| ordinal))
313    }
314
315    /// The record key at `ordinal`.
316    ///
317    /// # Errors
318    ///
319    /// When a read fails.
320    pub fn key(&self, ordinal: u32) -> Result<RecordKey, SegmentError> {
321        let (key, _) = self.units.entry(ordinal)?;
322        let bytes = <[u8; Digest128::LEN]>::try_from(key.as_slice())
323            .map_err(|_| malformed(self.segment, "a record key has the wrong width"))?;
324        Ok(RecordKey::from_digest(Digest128::from_bytes(bytes)))
325    }
326
327    /// The surface bytes of the record at `ordinal`.
328    ///
329    /// # Errors
330    ///
331    /// When a read fails or a block fails its checksum.
332    pub fn surface(&self, ordinal: u32) -> Result<Vec<u8>, SegmentError> {
333        let (_, location) = self.units.entry(ordinal)?;
334        let end = location
335            .offset
336            .checked_add(u64::from(location.len))
337            .ok_or_else(|| malformed(self.segment, "a surface's range overflows"))?;
338        self.segment.read_range(self.surfaces, location.offset..end)
339    }
340
341    /// The body bytes of the record at `ordinal`, unpacked.
342    ///
343    /// # Errors
344    ///
345    /// When a read fails, a block fails its checksum, or the stored body
346    /// does not unpack to its recorded length.
347    pub fn body(&self, ordinal: u32) -> Result<Vec<u8>, SegmentError> {
348        packed::read(self.segment, self.bodies, self.index, ordinal)
349    }
350
351    /// The whole record at `ordinal`.
352    ///
353    /// # Errors
354    ///
355    /// As [`surface`](Self::surface) and [`body`](Self::body), and when the
356    /// parts do not decode.
357    pub fn record(&self, ordinal: u32) -> Result<ContentRecord, ContentReadError> {
358        let surface = self.surface(ordinal)?;
359        let body = self.body(ordinal)?;
360        Ok(ContentRecord::decode(&surface, &body)?)
361    }
362
363    /// The TODO markers of the record at `ordinal`, read from its surface
364    /// part alone (see [`ContentRecord::todos_of`]).
365    ///
366    /// # Errors
367    ///
368    /// As [`surface`](Self::surface), and when the markers do not decode.
369    pub fn todos(&self, ordinal: u32) -> Result<Option<TodoMarkers>, ContentReadError> {
370        Ok(ContentRecord::todos_of(&self.surface(ordinal)?)?)
371    }
372}
373
374/// Why a stored record could not be read.
375#[derive(Debug, thiserror::Error)]
376pub enum ContentReadError {
377    #[error(transparent)]
378    Segment(#[from] SegmentError),
379    #[error(transparent)]
380    Decode(#[from] DecodeError),
381}
382
383fn malformed(segment: &Segment, reason: &'static str) -> SegmentError {
384    SegmentError::new(segment.path(), ErrorKind::Malformed(reason))
385}
386
387#[cfg(test)]
388pub(super) mod tests {
389    use std::sync::Arc;
390
391    use super::*;
392    use crate::cache::BlockCache;
393    use crate::content::{Body, RecordBody, RefKind, Reference, Surface, TodoMarker, TodoMarkers};
394    use crate::ids::{ContentKey, FamilyId, SegmentId, WriterIncarnation};
395    use crate::segment::{BLOCK_LEN, SegmentMeta};
396
397    pub(in crate::content) fn record(index: u32) -> ContentRecord {
398        let reference = Reference {
399            ordinal: index,
400            kind: RefKind::Call,
401            caller_symbol: Some(format!("caller_{index}")),
402            short_name: Some("target".into()),
403            full_ref: Some(format!("module::target_{}", index % 7)),
404            module_path: None,
405            line: index,
406            byte_start: 10,
407            byte_end: 20,
408            path_override: None,
409            local_name: None,
410            requested_name: None,
411            namespace_alias: None,
412            wildcard: false,
413            import_kind: None,
414        };
415        ContentRecord {
416            language: "rust".into(),
417            extractor_version: "v1".into(),
418            data: RecordBody::Parsed {
419                surface: Box::new(Surface {
420                    exported_symbols: vec![format!("item_{index}")],
421                    ..Surface::default()
422                }),
423                // Bodies of all sizes: some compress, some do not.
424                body: Box::new(Body {
425                    references: vec![reference; index as usize % 40],
426                    ..Body::default()
427                }),
428            },
429            // Every third record holds TODO markers, read back on their own
430            // by `todos`.
431            todos: (index % 3 == 0).then(|| TodoMarkers {
432                language: "rust".into(),
433                items: Some(vec![TodoMarker {
434                    line: index,
435                    marker: "TODO".into(),
436                    author: None,
437                    text: format!("item {index}"),
438                }]),
439            }),
440        }
441    }
442
443    #[test]
444    fn records_are_found_by_key_and_read_back_whole() {
445        let dir = tempfile::tempdir().unwrap();
446        let family = FamilyId::from_digest(Digest128::of(b"family"));
447        let path = dir.path().join("1.seg");
448        let mut writer = SegmentWriter::create(
449            &path,
450            SegmentMeta {
451                family,
452                segment: SegmentId::new(1),
453                incarnation: WriterIncarnation::new(1),
454                created_unix_ms: 0,
455            },
456        )
457        .unwrap();
458        let key = |index: u32| {
459            RecordKey::new(
460                ContentKey::of(format!("content {index}").as_bytes()),
461                "rust",
462                "v1",
463            )
464        };
465        let mut builder = ContentSectionsBuilder::new();
466        for index in 0..300 {
467            builder.add(key(index), &record(index));
468        }
469        builder.write(&mut writer).unwrap();
470        writer.finish().unwrap();
471        let segment = Segment::open(
472            &path,
473            family,
474            &KNOWN,
475            Arc::new(BlockCache::new(8 * BLOCK_LEN)),
476        )
477        .unwrap();
478        let content = ContentSegment::open(&segment).unwrap().unwrap();
479        assert_eq!(content.len(), 300);
480        for index in 0..300 {
481            let ordinal = content.find(key(index)).unwrap().unwrap();
482            assert_eq!(content.key(ordinal).unwrap(), key(index));
483            assert_eq!(content.record(ordinal).unwrap(), record(index));
484            assert_eq!(content.todos(ordinal).unwrap(), record(index).todos);
485        }
486        assert_eq!(
487            content
488                .find(RecordKey::new(ContentKey::of(b"content 1"), "rust", "v2"))
489                .unwrap(),
490            None,
491            "another extractor version is another record"
492        );
493    }
494}