Skip to main content

qualia_core_db/bundle/stream/publish/
owner.rs

1use crate::bundle::stream::descriptor::*;
2use crate::bundle::stream::index::{
3    AdmittedIndex, EntryScratch, ExtentLimit, admit_header, admit_index,
4};
5use crate::bundle::{BundleReadLimits, BundleReader};
6use crate::crypto::network::{cose::MAX_ENVELOPE_BYTES, digest::sha384};
7use crate::net::qdnf::types::StrongDigest;
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub struct EntryAssignment {
10    pub id: u32,
11    pub inner_version: u64,
12}
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum PublicationClass {
15    PlainCandidate,
16    PrivateProjection,
17    RecipientWrapped,
18}
19#[derive(Clone, Copy, Debug)]
20pub struct PublisherOptions {
21    pub parameters: ContextParameters,
22    pub class: PublicationClass,
23    pub metadata_limit: usize,
24}
25pub struct PlainPublisher<'a, 's> {
26    pub(super) source: &'a [u8],
27    pub(super) index: AdmittedIndex<'a>,
28    pub(super) assignments: &'a [EntryAssignment],
29    pub(super) parameters: ContextParameters,
30    pub(super) source_commit: SourceCommit,
31    pub(super) context_refs: &'s mut [PageRef],
32    pub(super) entry_refs: &'s mut [PageRef],
33    pub(super) context_next: usize,
34    pub(super) entry_next: usize,
35    pub(super) context_id: Option<StrongDigest>,
36    pub(super) used: usize,
37    pub(super) limit: usize,
38    pub(super) poisoned: bool,
39    pub(super) completed: Option<CandidateIdentity>,
40}
41impl<'a, 's> PlainPublisher<'a, 's> {
42    /// Prepare a structurally validated publication candidate.
43    /// For mapped/external storage the caller must retain an immutable snapshot
44    /// with writer exclusion for this publisher's entire lifetime. A Rust slice
45    /// alone does not establish exclusion against external writers.
46    /// Page/outboard sinks stage candidates only: authority, disclosure policy
47    /// and durable commit must succeed before public delivery or promotion.
48    pub fn prepare(
49        source: &'a [u8],
50        limits: BundleReadLimits,
51        assignments: &'a [EntryAssignment],
52        options: PublisherOptions,
53        index_scratch: &mut [EntryScratch<'a>],
54        id_scratch: &mut [u32],
55        context_refs: &'s mut [PageRef],
56        entry_refs: &'s mut [PageRef],
57    ) -> Result<Self, DescriptorError> {
58        if options.class != PublicationClass::PlainCandidate {
59            return Err(DescriptorError::Unsupported);
60        }
61        options.parameters.validate()?;
62        if options.metadata_limit > MAX_METADATA || options.metadata_limit < MAX_ENVELOPE_BYTES {
63            return Err(DescriptorError::Limit);
64        }
65        if assignments.len() > MAX_ENTRIES {
66            return Err(DescriptorError::Limit);
67        }
68        let limits = BundleReadLimits {
69            entries: limits.entries.min(MAX_ENTRIES),
70            index_bytes: limits.index_bytes.min(MAX_METADATA),
71            decoded_index_bytes: limits.decoded_index_bytes.min(MAX_METADATA),
72            ..limits
73        };
74        let ids = id_scratch
75            .get_mut(..assignments.len())
76            .ok_or(DescriptorError::Capacity)?;
77        for (out, a) in ids.iter_mut().zip(assignments) {
78            *out = a.id;
79        }
80        ids.sort_unstable();
81        if ids.windows(2).any(|w| w[0] == w[1]) {
82            return Err(DescriptorError::DuplicateId);
83        }
84        if index_scratch.len() < assignments.len() {
85            return Err(DescriptorError::Capacity);
86        }
87        let pages = assignments.len().div_ceil(PAGE_ROWS);
88        if context_refs.len() < pages || entry_refs.len() < pages {
89            return Err(DescriptorError::Capacity);
90        }
91        let extent = u64::try_from(source.len()).map_err(|_| DescriptorError::Overflow)?;
92        let header_bytes = source.get(..64).ok_or(DescriptorError::Source)?;
93        let header = admit_header(header_bytes, extent, ExtentLimit::default(), limits.into())
94            .map_err(|_| DescriptorError::Source)?;
95        let start =
96            usize::try_from(header.index_offset()).map_err(|_| DescriptorError::Overflow)?;
97        let index_bytes = source.get(start..).ok_or(DescriptorError::Source)?;
98        let index = admit_index(&header, index_bytes, limits.into(), index_scratch)
99            .map_err(|_| DescriptorError::Source)?;
100        // Cold owned metadata remains bounded/fallible, and is dropped before retaining this publisher.
101        {
102            let full = BundleReader::parse_with_limits(source, limits)
103                .map_err(|_| DescriptorError::Source)?;
104            if full.entries().len() != assignments.len() {
105                return Err(DescriptorError::Coverage);
106            }
107        }
108        let source_commit = SourceCommit {
109            length: extent,
110            version: header.probe().version,
111            flags: header.probe().flags,
112            header_digest: sha384(header_bytes),
113            index_offset: header.index_offset(),
114            index_length: header.index_length(),
115            index_digest: sha384(index_bytes),
116            source_digest: sha384(source),
117        };
118        context_refs[..pages].fill(PageRef::EMPTY);
119        entry_refs[..pages].fill(PageRef::EMPTY);
120        Ok(Self {
121            source,
122            index,
123            assignments,
124            parameters: options.parameters,
125            source_commit,
126            context_refs,
127            entry_refs,
128            context_next: 0,
129            entry_next: 0,
130            context_id: None,
131            used: MAX_ENVELOPE_BYTES,
132            limit: options.metadata_limit,
133            poisoned: false,
134            completed: None,
135        })
136    }
137    pub fn page_count(&self) -> usize {
138        self.assignments.len().div_ceil(PAGE_ROWS)
139    }
140    pub fn entry_count(&self) -> usize {
141        self.assignments.len()
142    }
143    pub const fn is_poisoned(&self) -> bool {
144        self.poisoned
145    }
146    pub const fn context_id(&self) -> Option<StrongDigest> {
147        self.context_id
148    }
149    pub const fn source_commit(&self) -> SourceCommit {
150        self.source_commit
151    }
152    pub const fn metadata_reserved_bytes(&self) -> usize {
153        self.used
154    }
155    pub(super) fn live(&self) -> Result<(), DescriptorError> {
156        if self.poisoned {
157            Err(DescriptorError::Poisoned)
158        } else {
159            Ok(())
160        }
161    }
162    pub(super) fn charge(&self, n: usize) -> Result<usize, DescriptorError> {
163        self.used
164            .checked_add(n)
165            .filter(|v| *v <= self.limit)
166            .ok_or(DescriptorError::Limit)
167    }
168}