Skip to main content

mito2/series_index/samples/
metadata.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Explicit sample framing and bounded two-level metadata pages.
16
17use crate::error::Result;
18use crate::series_index::samples::codec::{self, Cursor, put_u32, put_u64};
19use crate::series_index::samples::{
20    Manifest, MetricSeriesId, VERSION, histogram, invalid, require, unsupported, valid_rows,
21};
22
23pub(super) const MAGIC: &[u8; 8] = b"GTSAMPLE";
24pub(super) const HEADER_SIZE: u64 = 16;
25pub(super) const FOOTER_SIZE: u64 = 16;
26const FOOTER_MAGIC: &[u8; 8] = b"NARTGRP1";
27/// Limit a single directory fetch even for a malformed footer.
28pub(super) const MAX_GROUPS: usize = (8 * 1024 * 1024) / GROUP_BYTES;
29pub(super) const PAGE_LIMIT: usize = 65536;
30pub(super) const ROOT_CAPACITY: usize = (PAGE_LIMIT - 12) / 64;
31/// Largest decoded block payload, and therefore the largest frame a decoder has to decompress.
32pub(super) const CHUNK_LIMIT: usize = 1024 * 1024;
33/// Fixed part of a block descriptor, before its 36-byte column descriptors.
34///
35/// The exact series key is not part of it. A descriptor keeps a fixed-size [`KeyRef`] into
36/// the group's key area instead, so descriptor size is independent of key length and a key
37/// longer than a metadata page is representable.
38pub(super) const BLOCK_FIXED_BYTES: usize = 56;
39/// Smallest possible block descriptor: the fixed part plus its three mandatory columns.
40const MIN_BLOCK_BYTES: usize = BLOCK_FIXED_BYTES + 3 * 36;
41
42/// Descriptor bytes for a block with `columns` column descriptors.
43///
44/// Independent of the key's length: the descriptor references the key, it does not hold it.
45/// This is the one place the descriptor size formula lives, for the writer's page planning
46/// and for readers that inspect decoded pages.
47pub(super) fn descriptor_bytes(columns: usize) -> usize {
48    BLOCK_FIXED_BYTES + 36 * columns
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52pub(crate) struct PayloadReference {
53    pub offset: u64,
54    pub stored: u32,
55    pub decoded: u32,
56    pub encoding: u16,
57    pub compression: u16,
58}
59impl PayloadReference {
60    pub fn end(&self) -> Result<u64> {
61        self.offset
62            .checked_add(u64::from(self.stored))
63            .ok_or_else(|| invalid("sample payload offset overflow"))
64    }
65    pub fn validate(&self, start: u64, end: u64, page: bool) -> Result<()> {
66        let limit = if page { PAGE_LIMIT } else { CHUNK_LIMIT };
67        require(
68            self.stored > 0
69                && self.decoded > 0
70                && self.decoded as usize <= limit
71                && self.stored as usize <= limit + 65536,
72            "sample payload exceeds limits",
73        )?;
74        require(
75            self.offset >= start && self.end()? <= end,
76            "sample payload outside area",
77        )?;
78        if self.compression == 0 {
79            require(self.stored == self.decoded, "raw samples length mismatch")?;
80        }
81        Ok(())
82    }
83    fn encode(&self, out: &mut Vec<u8>) {
84        put_u64(out, self.offset);
85        put_u32(out, self.stored);
86        put_u32(out, self.decoded);
87        out.extend(self.encoding.to_le_bytes());
88        out.extend(self.compression.to_le_bytes());
89        put_u32(out, 0);
90    }
91    fn decode(c: &mut Cursor<'_>) -> Result<Self> {
92        let result = Self {
93            offset: c.u64()?,
94            stored: c.u32()?,
95            decoded: c.u32()?,
96            encoding: c.u16()?,
97            compression: c.u16()?,
98        };
99        require(c.u32()? == 0, "nonzero sample payload reserved field")?;
100        Ok(result)
101    }
102    fn validate_payload(&self, bytes: &[u8]) -> Result<()> {
103        require(
104            bytes.len() == self.stored as usize,
105            "sample stored length mismatch",
106        )
107    }
108    pub fn unpack(&self, bytes: &[u8]) -> Result<Vec<u8>> {
109        self.validate_payload(bytes)?;
110        codec::decompress(bytes, self.compression, self.decoded as usize)
111    }
112    pub fn unpack_with_decoder<'a>(
113        &self,
114        bytes: &'a [u8],
115        decoder: &'a mut codec::PayloadDecoder,
116    ) -> Result<&'a [u8]> {
117        self.validate_payload(bytes)?;
118        decoder.decompress(bytes, self.compression, self.decoded as usize)
119    }
120}
121const SMALL_CHUNK_BYTES: usize = 128;
122
123/// Pack the last encoded column in place, keeping its offset within the block buffer.
124pub(super) fn pack_chunk_tail(
125    compressor: &mut zstd::bulk::Compressor<'_>,
126    buffer: &mut Vec<u8>,
127    compressed: &mut Vec<u8>,
128    start: usize,
129    encoding: u16,
130) -> Result<PayloadReference> {
131    let raw = &buffer[start..];
132    let decoded = raw.len();
133    require(
134        decoded > 0 && decoded <= CHUNK_LIMIT,
135        "sample encoded payload exceeds limit",
136    )?;
137    let mut compression = 0;
138    if decoded > SMALL_CHUNK_BYTES {
139        compressed.clear();
140        compressed.reserve(zstd::zstd_safe::compress_bound(decoded));
141        compressor
142            .compress_to_buffer(raw, compressed)
143            .map_err(|e| invalid(format!("sample compression: {e}")))?;
144        if compressed.len() < decoded {
145            compression = 1;
146            buffer.truncate(start);
147            buffer.extend_from_slice(compressed);
148        }
149    }
150    let stored = &buffer[start..];
151    let reference = PayloadReference {
152        offset: start as u64,
153        stored: stored.len() as u32,
154        decoded: decoded as u32,
155        encoding,
156        compression,
157    };
158    reference.validate(reference.offset, reference.end()?, false)?;
159    Ok(reference)
160}
161
162pub(super) fn pack_page_into<'a>(
163    compressor: &mut zstd::bulk::Compressor<'_>,
164    raw: &'a [u8],
165    compressed: &'a mut Vec<u8>,
166    offset: u64,
167) -> Result<(PayloadReference, &'a [u8])> {
168    require(
169        !raw.is_empty() && raw.len() <= PAGE_LIMIT,
170        "sample encoded payload exceeds limit",
171    )?;
172    compressed.clear();
173    compressed.reserve(zstd::zstd_safe::compress_bound(raw.len()));
174    compressor
175        .compress_to_buffer(raw, compressed)
176        .map_err(|e| invalid(format!("sample compression: {e}")))?;
177    let (compression, stored) = if compressed.len() < raw.len() {
178        (1, compressed.as_slice())
179    } else {
180        (0, raw)
181    };
182    let reference = PayloadReference {
183        offset,
184        stored: stored.len() as u32,
185        decoded: raw.len() as u32,
186        encoding: 1,
187        compression,
188    };
189    reference.validate(offset, reference.end()?, true)?;
190    Ok((reference, stored))
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
194pub(crate) struct Bounds {
195    pub first: MetricSeriesId,
196    pub last: MetricSeriesId,
197    pub min: i64,
198    pub max: i64,
199}
200impl Bounds {
201    pub fn validate(&self) -> Result<()> {
202        require(
203            self.first <= self.last && self.min <= self.max,
204            "reversed sample bounds",
205        )
206    }
207    pub fn extend(&mut self, next: Self) {
208        self.last = next.last;
209        self.min = self.min.min(next.min);
210        self.max = self.max.max(next.max);
211    }
212    fn encode(&self, out: &mut Vec<u8>) {
213        for id in [self.first, self.last] {
214            put_u32(out, id.table_id);
215            put_u64(out, id.tsid);
216        }
217        put_u64(out, self.min as u64);
218        put_u64(out, self.max as u64);
219    }
220    fn decode(c: &mut Cursor<'_>) -> Result<Self> {
221        let result = Self {
222            first: MetricSeriesId {
223                table_id: c.u32()?,
224                tsid: c.u64()?,
225            },
226            last: MetricSeriesId {
227                table_id: c.u32()?,
228                tsid: c.u64()?,
229            },
230            min: c.u64()? as i64,
231            max: c.u64()? as i64,
232        };
233        result.validate()?;
234        Ok(result)
235    }
236}
237#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
238pub(crate) struct PageReference {
239    pub bounds: Bounds,
240    pub payload: PayloadReference,
241}
242impl PageReference {
243    fn encode(&self, out: &mut Vec<u8>) {
244        self.bounds.encode(out);
245        self.payload.encode(out);
246    }
247    fn decode(c: &mut Cursor<'_>) -> Result<Self> {
248        let reference = Self {
249            bounds: Bounds::decode(c)?,
250            payload: PayloadReference::decode(c)?,
251        };
252        if reference.payload.encoding != 1 || reference.payload.compression > 1 {
253            return Err(unsupported("samples metadata codec"));
254        }
255        Ok(reference)
256    }
257}
258#[derive(Debug, Clone)]
259pub(super) struct Column {
260    pub role: u32,
261    pub id: u32,
262    pub payload: PayloadReference,
263    pub nulls: u32,
264}
265/// The location of one exact series key inside a group's key area.
266///
267/// This reference is the descriptor's whole identity. The key bytes themselves are stored
268/// once per series in the group's key area, outside every bounded metadata page, so a key may
269/// be longer than a page and the descriptor stays 12 bytes whatever its length is.
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub(super) struct KeyRef {
272    /// On disk, the group's `payload_end` plus the first key byte's offset in the decompressed key stream.
273    pub offset: u64,
274    /// Key length in bytes; nonzero.
275    pub length: u32,
276}
277
278impl KeyRef {
279    pub fn end(&self) -> Result<u64> {
280        self.offset
281            .checked_add(u64::from(self.length))
282            .ok_or_else(|| invalid("sample key offset overflow"))
283    }
284
285    fn encode(&self, out: &mut Vec<u8>) {
286        put_u64(out, self.offset);
287        put_u32(out, self.length);
288    }
289
290    fn decode(c: &mut Cursor<'_>) -> Result<Self> {
291        Ok(Self {
292            offset: c.u64()?,
293            length: c.u32()?,
294        })
295    }
296
297    /// Requires this reference to name a nonempty key entry inside `area`.
298    ///
299    pub fn validate(&self, area: KeyArea) -> Result<()> {
300        require(
301            self.length > 0 && self.offset >= area.start && self.end()? <= area.end,
302            "sample key reference outside key area",
303        )
304    }
305}
306
307/// A group's key area: exact series keys stored back to back, outside every metadata page.
308///
309/// Keys are appended in block order and are never page-bounded, so their length is bounded by
310/// the part, not by `PAGE_LIMIT`. Because blocks are
311/// ordered by exact key, every block of one series is adjacent and shares a single copy of the
312/// key, which makes an equal [`KeyRef`] mean "the same exact series".
313#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
314pub(crate) struct KeyArea {
315    pub start: u64,
316    pub end: u64,
317}
318
319/// The three regions of one group, in file order: column payloads, exact series keys, pages.
320#[derive(Debug, Clone, Copy)]
321pub(super) struct Areas {
322    pub payload_start: u64,
323    /// End of the column payload area and start of the key area.
324    pub payload_end: u64,
325    /// The key area every block descriptor references.
326    pub keys: KeyArea,
327    /// Start of the metadata area, which is the end of the key area.
328    pub metadata_start: u64,
329}
330
331#[derive(Debug, Clone)]
332pub(crate) struct Block {
333    /// Coarse `(table_id, tsid)` prefix decoded from the block's exact key.
334    ///
335    /// It prunes candidates but never names the owner: `(table_id, tsid)` is a hash, so two
336    /// distinct series can share it. The owner is the key [`Self::key`] references.
337    pub id: MetricSeriesId,
338    /// Fixed-size reference to the block's exact key in the group's key area.
339    ///
340    /// Equal references mean the same exact series; a different series that collides on the
341    /// identifier always carries a different reference.
342    pub(super) key: KeyRef,
343    pub min: i64,
344    pub max: i64,
345    pub ordinal: u64,
346    pub rows: u32,
347    pub(super) columns: Vec<Column>,
348}
349/// The ordering boundary retained between pages and groups, without column descriptors.
350///
351/// A [`KeyRef`] is an offset inside one group's key area, so two references are comparable only
352/// when they belong to the same group; `group` carries that scope in the boundary itself so no
353/// caller can compare references across a group boundary by accident. Two groups hold unrelated
354/// key areas, which is why a series that spans groups is recognised by [`BlockOrder::continues`]
355/// on the exact key bytes instead.
356#[derive(Debug, Clone, Copy, PartialEq, Eq)]
357pub(crate) struct BlockOrder {
358    group: u64,
359    id: MetricSeriesId,
360    key: KeyRef,
361    min: i64,
362    max: i64,
363    ordinal: u64,
364}
365
366impl BlockOrder {
367    /// The group this block belongs to.
368    pub(crate) fn group(&self) -> u64 {
369        self.group
370    }
371
372    /// The coarse `(table_id, tsid)` prefix, which is ordered across groups as well.
373    pub(crate) fn id(&self) -> MetricSeriesId {
374        self.id
375    }
376
377    /// The block's key reference, a location inside [`Self::group`]'s key area.
378    pub(super) fn key(&self) -> KeyRef {
379        self.key
380    }
381
382    /// Checks the next block of the *same* group against this boundary.
383    ///
384    /// Ownership and ordering of a group are decided on the exact `(table_id, tsid)` and on the
385    /// key reference only: two blocks of one group that share one reference share one key copy,
386    /// so they are one exact series, while a different series always has its own copy, placed
387    /// after the previous one and restarting the ordinal. Only descriptor fields are read, so a
388    /// block this request prunes is never fetched and its key content is not validated.
389    pub(crate) fn precedes(&self, next: &Self, adjacent: bool) -> Result<()> {
390        require(
391            self.group == next.group,
392            "sample key references compared across groups",
393        )?;
394        require(self.id <= next.id, "unordered sample series keys")?;
395        if next.key == self.key {
396            self.continues(next, adjacent)?;
397        } else {
398            // A different series must place its one key copy after the previous series' copy.
399            // Overlap, or a second copy of a key that is still current, is a corrupt reference
400            // rather than a silent second read of the same bytes.
401            require(
402                self.key.end()? <= next.key.offset,
403                "overlapping sample key references",
404            )?;
405            if adjacent {
406                require(next.ordinal == 0, "first sample block has nonzero ordinal")?;
407            }
408        }
409        Ok(())
410    }
411
412    /// Requires `next` to continue one exact series in time and ordinal.
413    ///
414    /// Equal exact key bytes are what make two blocks the same series across a group boundary,
415    /// where their references belong to different key areas. A repeated key that restarts its
416    /// ordinal or goes back in time is a corrupt group, not a second series.
417    pub(crate) fn continues(&self, next: &Self, adjacent: bool) -> Result<()> {
418        require(
419            self.max <= next.min && self.ordinal < next.ordinal,
420            "unordered sample blocks",
421        )?;
422        if adjacent {
423            require(
424                self.ordinal.checked_add(1) == Some(next.ordinal),
425                "nonconsecutive sample ordinal",
426            )?;
427        }
428        Ok(())
429    }
430}
431
432impl Block {
433    /// The ordering boundary this block contributes, scoped to its group.
434    pub(crate) fn order(&self, group: u64) -> BlockOrder {
435        BlockOrder {
436            group,
437            id: self.id,
438            key: self.key,
439            min: self.min,
440            max: self.max,
441            ordinal: self.ordinal,
442        }
443    }
444
445    /// Checks this block against the previous block of the same page.
446    ///
447    /// A page never spans groups, so both references name one key area and are comparable; a block
448    /// in another group is compared through [`BlockOrder::continues`] and its exact key instead.
449    fn follows_in_page(&self, previous: &Self, adjacent: bool) -> Result<()> {
450        // One scope for both sides: a page belongs to exactly one group, and no reference built
451        // here outlives the page.
452        const PAGE_SCOPE: u64 = 0;
453        previous
454            .order(PAGE_SCOPE)
455            .precedes(&self.order(PAGE_SCOPE), adjacent)
456    }
457
458    /// The coarse bounds used for pruning. Exact ownership lives in `key`.
459    pub fn bounds(&self) -> Bounds {
460        Bounds {
461            first: self.id,
462            last: self.id,
463            min: self.min,
464            max: self.max,
465        }
466    }
467    pub fn encode(&self, out: &mut Vec<u8>) {
468        put_u32(out, self.id.table_id);
469        put_u64(out, self.id.tsid);
470        self.key.encode(out);
471        put_u64(out, self.min as u64);
472        put_u64(out, self.max as u64);
473        put_u64(out, self.ordinal);
474        put_u32(out, self.rows);
475        put_u32(out, self.columns.len() as u32);
476        for column in &self.columns {
477            put_u32(out, column.role);
478            put_u32(out, column.id);
479            column.payload.encode(out);
480            put_u32(out, column.nulls);
481        }
482    }
483    fn decode(
484        c: &mut Cursor<'_>,
485        manifest: &Manifest,
486        areas: Areas,
487        previous_end: &mut u64,
488    ) -> Result<Self> {
489        let id = MetricSeriesId {
490            table_id: c.u32()?,
491            tsid: c.u64()?,
492        };
493        // Only the key's location is decoded here. The bytes stay in the key area, so a
494        // descriptor never grows with the key and a request that prunes this block never
495        // reads it; the reader validates the reference and its `(table_id, tsid)` prefix
496        // when it fetches the key for a block it actually selects.
497        let key = KeyRef::decode(c)?;
498        key.validate(areas.keys)?;
499        let min = c.u64()? as i64;
500        let max = c.u64()? as i64;
501        let ordinal = c.u64()?;
502        let rows = c.u32()?;
503        let count = c.u32()? as usize;
504        require(
505            min <= max && valid_rows(rows as usize, manifest.fields.len()),
506            "invalid sample block bounds/count",
507        )?;
508        require(
509            count >= 3 && count <= manifest.fields.len() + 3 && count <= c.remaining() / 36,
510            "invalid sample column count",
511        )?;
512        let mut columns = Vec::with_capacity(count);
513        let mut next_field = 0;
514        for index in 0..count {
515            let role = c.u32()?;
516            let column_id = c.u32()?;
517            let payload = PayloadReference::decode(c)?;
518            let nulls = c.u32()?;
519            if index < 3 {
520                require(
521                    role == index as u32 + 1
522                        && column_id
523                            == if index == 0 {
524                                manifest.timestamp.column_id
525                            } else {
526                                0
527                            }
528                        && nulls == 0,
529                    "invalid mandatory sample column",
530                )?;
531            } else {
532                require(
533                    role == 4 && nulls < rows,
534                    "invalid sample field role/null count",
535                )?;
536                let position = manifest.fields[next_field..]
537                    .iter()
538                    .position(|f| f.column_id == column_id)
539                    .ok_or_else(|| invalid("unknown or unordered sample field"))?
540                    + next_field;
541                next_field = position + 1;
542                // A known value encoding must be the one its field's type is stored with, so a
543                // chunk is never decoded as another kind of value.
544                if payload.encoding <= histogram::ENCODING {
545                    require(
546                        payload.encoding == manifest.fields[position].encoding()?,
547                        "sample field codec does not match its field type",
548                    )?;
549                }
550            }
551            if payload.encoding <= histogram::ENCODING {
552                let valid = match role {
553                    1 => matches!(payload.encoding, 1 | 2),
554                    2 => matches!(payload.encoding, 3 | 4),
555                    3 => matches!(payload.encoding, 6 | 7),
556                    4 => matches!(payload.encoding, 5 | histogram::ENCODING),
557                    _ => false,
558                };
559                require(valid, "sample codec role mismatch")?;
560            }
561            payload.validate(*previous_end, areas.payload_end, false)?;
562            *previous_end = payload.end()?;
563            columns.push(Column {
564                role,
565                id: column_id,
566                payload,
567                nulls,
568            });
569        }
570        Ok(Self {
571            id,
572            key,
573            min,
574            max,
575            ordinal,
576            rows,
577            columns,
578        })
579    }
580}
581#[derive(Debug)]
582pub(crate) enum Page {
583    Leaf(Vec<Block>),
584    Internal(Vec<PageReference>),
585}
586impl Page {
587    pub(crate) fn retained_size(&self) -> usize {
588        std::mem::size_of::<Self>()
589            + match self {
590                Self::Internal(children) => {
591                    children.capacity() * std::mem::size_of::<PageReference>()
592                }
593                Self::Leaf(blocks) => {
594                    blocks.capacity() * std::mem::size_of::<Block>()
595                        // Each block owns its column descriptors on the heap. Its exact
596                        // series key is not retained: it stays in the group's key area.
597                        + blocks
598                            .iter()
599                            .map(|block| block.columns.capacity() * std::mem::size_of::<Column>())
600                            .sum::<usize>()
601                }
602            }
603    }
604
605    pub fn bounds(&self) -> Result<Bounds> {
606        let bounds: Vec<_> = match self {
607            Self::Leaf(v) => v.iter().map(Block::bounds).collect(),
608            Self::Internal(v) => v.iter().map(|c| c.bounds).collect(),
609        };
610        let mut result = *bounds.first().ok_or_else(|| invalid("empty sample page"))?;
611        for bound in &bounds[1..] {
612            result.extend(*bound);
613        }
614        Ok(result)
615    }
616    #[cfg(test)]
617    pub fn encode(&self) -> Vec<u8> {
618        let mut out = Vec::new();
619        self.encode_into(&mut out);
620        out
621    }
622
623    pub(super) fn encode_into(&self, out: &mut Vec<u8>) {
624        out.clear();
625        match self {
626            Self::Leaf(v) => {
627                put_u32(out, 0);
628                put_u64(out, v.len() as u64);
629                for block in v {
630                    block.encode(out);
631                }
632            }
633            Self::Internal(v) => {
634                put_u32(out, 1);
635                put_u64(out, v.len() as u64);
636                for child in v {
637                    child.encode(out);
638                }
639            }
640        }
641    }
642    /// Decodes one metadata page.
643    ///
644    /// `areas` bounds what the page may reference: column payloads end where the key area
645    /// starts, keys live in their own area, and the page area starts at `areas.metadata_start`
646    /// so every child page must lie after it and before its parent.
647    pub(super) fn decode(
648        bytes: &[u8],
649        reference: &PageReference,
650        depth: u32,
651        areas: Areas,
652        manifest: &Manifest,
653    ) -> Result<Self> {
654        require(bytes.len() <= PAGE_LIMIT, "sample page exceeds limit")?;
655        let mut c = Cursor::new(bytes);
656        let kind = c.u32()?;
657        let count = c.length()?;
658        require(count > 0, "empty sample page")?;
659        let page = match (kind, depth) {
660            (0, 1) => {
661                require(
662                    count <= c.remaining() / MIN_BLOCK_BYTES,
663                    "sample block count exceeds page",
664                )?;
665                let mut blocks: Vec<Block> = Vec::with_capacity(count);
666                let mut end = areas.payload_start;
667                for _ in 0..count {
668                    let block = Block::decode(&mut c, manifest, areas, &mut end)?;
669                    if let Some(previous) = blocks.last() {
670                        block.follows_in_page(previous, true)?;
671                    }
672                    blocks.push(block);
673                }
674                Self::Leaf(blocks)
675            }
676            (1, 2) => {
677                require(
678                    count <= ROOT_CAPACITY && count <= c.remaining() / 64,
679                    "sample root exceeds capacity",
680                )?;
681                let mut children: Vec<PageReference> = Vec::with_capacity(count);
682                let mut end = areas.metadata_start;
683                for _ in 0..count {
684                    let child = PageReference::decode(&mut c)?;
685                    child
686                        .payload
687                        .validate(end, reference.payload.offset, true)?;
688                    end = child.payload.end()?;
689                    if let Some(previous) = children.last() {
690                        require(
691                            previous.bounds.last <= child.bounds.first,
692                            "unordered sample child ranges",
693                        )?;
694                    }
695                    children.push(child);
696                }
697                Self::Internal(children)
698            }
699            _ => return Err(unsupported("samples metadata kind/depth")),
700        };
701        c.end()?;
702        require(
703            page.bounds()? == reference.bounds,
704            "samples page bounds disagree with parent",
705        )?;
706        Ok(page)
707    }
708}
709pub(super) fn header() -> Vec<u8> {
710    let mut out = MAGIC.to_vec();
711    put_u32(&mut out, VERSION);
712    put_u32(&mut out, 0);
713    out
714}
715pub(super) fn validate_header(bytes: &[u8]) -> Result<()> {
716    let mut c = Cursor::new(bytes);
717    require(c.take(8)? == MAGIC, "sample header magic")?;
718    if c.u32()? != VERSION {
719        return Err(unsupported("samples file version"));
720    }
721    require(c.u32()? == 0, "nonzero sample header reserved field")?;
722    c.end()
723}
724/// One part-directory entry. The first group starts after the header; subsequent
725/// groups start at the end of the preceding root page.
726pub(super) const GROUP_BYTES: usize = 64 + 4 + 5 * 8;
727#[derive(Debug, Clone)]
728pub(crate) struct Group {
729    pub start: u64,
730    pub rows: u64,
731    pub blocks: u64,
732    pub root: PageReference,
733    pub depth: u32,
734    pub payload_end: u64,
735    pub key_end: u64,
736    pub logical_key_end: u64,
737}
738impl Group {
739    pub fn keys(&self) -> KeyArea {
740        KeyArea {
741            start: self.payload_end,
742            end: self.logical_key_end,
743        }
744    }
745
746    /// The group's three regions, as page decoding needs them.
747    pub(super) fn areas(&self) -> Areas {
748        Areas {
749            payload_start: self.start,
750            payload_end: self.payload_end,
751            keys: self.keys(),
752            metadata_start: self.key_end,
753        }
754    }
755
756    fn encode(&self, out: &mut Vec<u8>) {
757        self.root.encode(out);
758        put_u32(out, self.depth);
759        for value in [
760            self.payload_end,
761            self.key_end,
762            self.logical_key_end,
763            self.rows,
764            self.blocks,
765        ] {
766            put_u64(out, value);
767        }
768    }
769}
770/// Encodes the directory followed by its fixed-size footer.
771pub(super) fn encode_directory(groups: &[Group]) -> Vec<u8> {
772    let mut bytes = Vec::with_capacity(groups.len() * GROUP_BYTES + FOOTER_SIZE as usize);
773    for group in groups {
774        group.encode(&mut bytes);
775    }
776    let length = bytes.len() as u64;
777    bytes.extend(FOOTER_MAGIC);
778    put_u64(&mut bytes, length);
779    bytes
780}
781
782pub(super) struct DirectoryFooter {
783    pub length: u64,
784}
785impl DirectoryFooter {
786    pub fn decode(bytes: &[u8]) -> Result<Self> {
787        let mut c = Cursor::new(bytes);
788        require(c.take(8)? == FOOTER_MAGIC, "invalid sample directory magic")?;
789        let length = c.u64()?;
790        require(
791            length > 0
792                && length <= (MAX_GROUPS * GROUP_BYTES) as u64
793                && length.is_multiple_of(GROUP_BYTES as u64),
794            "invalid sample directory length",
795        )?;
796        c.end()?;
797        Ok(Self { length })
798    }
799
800    pub fn groups(&self, bytes: &[u8], end: u64) -> Result<Vec<Group>> {
801        require(
802            bytes.len() as u64 == self.length,
803            "invalid sample directory length",
804        )?;
805        let mut start = HEADER_SIZE;
806        let mut c = Cursor::new(bytes);
807        let mut groups: Vec<Group> = Vec::with_capacity(bytes.len() / GROUP_BYTES);
808        while c.remaining() > 0 {
809            let root = PageReference::decode(&mut c)?;
810            let depth = c.u32()?;
811            let payload_end = c.u64()?;
812            let key_end = c.u64()?;
813            let logical_key_end = c.u64()?;
814            let rows = c.u64()?;
815            let blocks = c.u64()?;
816            let next = root.payload.end()?;
817            require(
818                (1..=2).contains(&depth)
819                    && rows >= blocks
820                    && blocks > 0
821                    && start < payload_end
822                    && payload_end < logical_key_end
823                    && payload_end < key_end
824                    && next <= end,
825                "invalid sample group boundaries",
826            )?;
827            root.payload.validate(key_end, next, true)?;
828            if let Some(previous) = groups.last() {
829                require(
830                    previous.root.bounds.last <= root.bounds.first,
831                    "unordered sample groups",
832                )?;
833            }
834            groups.push(Group {
835                start,
836                rows,
837                blocks,
838                root,
839                depth,
840                payload_end,
841                key_end,
842                logical_key_end,
843            });
844            start = next;
845        }
846        require(start == end, "sample directory does not follow last group")?;
847        Ok(groups)
848    }
849}