Skip to main content

ic_db/
named_schema.rs

1//! Finite compiled named-type graph. No persisted catalog or materialized value tree.
2
3use crate::{
4    Error, FieldSchema, FieldType,
5    codec::{Decoder, Encoder},
6    schema::{MAX_FIELDS, encode_type, name},
7};
8use std::collections::{BTreeMap, BTreeSet};
9
10pub(crate) const MAX_DEPTH: usize = 32;
11pub(crate) const MAX_NODES: usize = 256;
12pub(crate) const MAX_COLLECTION_ITEMS: usize = 256;
13
14/// Compiler-resolved link. Names carry identity; the function breaks constant cycles.
15#[derive(Clone, Copy, Debug)]
16pub struct TypeLink {
17    /// Logical name under the stored contract.
18    pub name: &'static str,
19    /// Resolve the compiled definition, never stored or dynamically loaded code.
20    pub definition: fn() -> &'static TypeSchema,
21}
22impl PartialEq for TypeLink {
23    fn eq(&self, other: &Self) -> bool {
24        self.name == other.name
25    }
26}
27impl Eq for TypeLink {}
28
29/// Named schema; its links are shallow so recursive graphs never expand on comparison.
30#[derive(Debug, PartialEq, Eq)]
31pub struct TypeSchema {
32    /// Logical type identity.
33    pub name: &'static str,
34    /// The complete named value shape, including any wrapped type and its bounds.
35    pub body: TypeBody,
36}
37/// A versioned constraint on the inner primitive of a named newtype.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum NewtypeRule {
40    /// A Principal other than the anonymous identity.
41    NonAnonymous,
42    /// Bounded UTF-8 text with a conjunction of optional refinements.
43    Text {
44        /// Inner primitive byte limit.
45        max_bytes: u32,
46        /// Require at least one scalar outside Unicode White_Space.
47        non_blank: bool,
48        /// Maximum number of Unicode scalar values.
49        max_chars: Option<u32>,
50    },
51}
52
53impl NewtypeRule {
54    /// The existing primitive used for storage and ordering.
55    #[must_use]
56    pub const fn primitive(self) -> FieldType {
57        match self {
58            Self::NonAnonymous => FieldType::Principal,
59            Self::Text { max_bytes, .. } => FieldType::Text { max_bytes },
60        }
61    }
62    pub(crate) fn check_text(self, text: &str) -> Result<(), Error> {
63        let mut check = self.text_check().ok_or(Error::InvalidOperand)?;
64        check.segment(text)?;
65        check.finish()
66    }
67
68    pub(crate) fn text_check(self) -> Option<TextCheck> {
69        match self {
70            Self::Text {
71                max_bytes,
72                non_blank,
73                max_chars,
74            } => Some(TextCheck {
75                bytes_left: max_bytes as usize,
76                chars_left: max_chars.filter(|n| *n < max_bytes).map(|n| n as usize),
77                needs_non_blank: non_blank,
78            }),
79            Self::NonAnonymous => None,
80        }
81    }
82}
83
84// Ordered index text can arrive in segments separated by escaped NUL bytes.
85pub(crate) struct TextCheck {
86    bytes_left: usize,
87    chars_left: Option<usize>,
88    needs_non_blank: bool,
89}
90
91impl TextCheck {
92    pub(crate) fn segment(&mut self, text: &str) -> Result<(), Error> {
93        self.bytes_left = self
94            .bytes_left
95            .checked_sub(text.len())
96            .ok_or(Error::Limit)?;
97        if let Some(left) = &mut self.chars_left {
98            *left = left
99                .checked_sub(text.chars().count())
100                .ok_or(Error::InvalidOperand)?;
101        }
102        // Unicode White_Space, fixed for version one of non_blank.
103        if self.needs_non_blank {
104            self.needs_non_blank = text.chars().all(|c| matches!(c as u32, 0x09..=0x0d | 0x20 | 0x85 | 0xa0 | 0x1680 | 0x2000..=0x200a | 0x2028..=0x2029 | 0x202f | 0x205f | 0x3000));
105        }
106        Ok(())
107    }
108
109    pub(crate) fn finish(self) -> Result<(), Error> {
110        if self.needs_non_blank {
111            Err(Error::InvalidOperand)
112        } else {
113            Ok(())
114        }
115    }
116}
117
118impl FieldType {
119    pub(crate) fn newtype_rule(self) -> Option<NewtypeRule> {
120        if let Self::Named(link) = self
121            && let TypeBody::Checked(rule) = (link.definition)().body
122        {
123            return Some(rule);
124        }
125        None
126    }
127}
128/// A compiled named type; record/enum members use canonical name order.
129#[derive(Debug, PartialEq, Eq)]
130pub enum TypeBody {
131    /// Named wrapper around a primitive or a bounded ordered list.
132    Wrapped(FieldType),
133    /// Scalar wrapper whose values must satisfy the declared rule.
134    Checked(NewtypeRule),
135    /// Canonical map with scalar/unit-enum keys and arbitrary admitted value shapes.
136    Map {
137        /// Required primitive, scalar newtype or unit-enum key.
138        key: FieldType,
139        /// Value type and optionality, independent of map presence.
140        value: ValueSchema,
141        /// Maximum entries, sharing the enclosing row's collection budget.
142        max_items: u32,
143    },
144    /// Canonical scalar/unit-enum set. Stored elements must be strictly increasing.
145    Set {
146        /// Primitive, scalar newtype or unit enum with a strict logical order.
147        item: FieldType,
148        /// Maximum entries, also subject to the enclosing row's shared budget.
149        max_items: u32,
150    },
151    /// Stored fields; nested entity references are not supported.
152    Record(&'static [FieldSchema]),
153    /// Named alternatives, each with at most one typed payload.
154    Enum(&'static [VariantSchema]),
155}
156/// One unit or payload variant.
157#[derive(Debug, PartialEq, Eq)]
158pub struct VariantSchema {
159    /// Logical variant identity.
160    pub name: &'static str,
161    /// None means a unit variant, distinct from an optional absent payload.
162    pub payload: Option<ValueSchema>,
163}
164
165// Ordered capability belongs to the complete enum, including unused variants.
166// Bound unchecked operand definitions before comparing them with admitted metadata.
167pub(crate) fn unit_enum_len(definition: &TypeSchema) -> Option<usize> {
168    let TypeBody::Enum(variants) = &definition.body else {
169        return None;
170    };
171
172    (!definition.name.is_empty()
173        && definition.name.len() <= 64
174        && !variants.is_empty()
175        && variants.len() <= 64
176        && variants
177            .iter()
178            .all(|v| v.payload.is_none() && !v.name.is_empty() && v.name.len() <= 64)
179        && variants.windows(2).all(|w| w[0].name < w[1].name))
180    .then_some(variants.len())
181}
182/// Payload shape, shared with the field type/optionality rules.
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub struct ValueSchema {
185    /// Exact scalar, bounded list or compiler-resolved named type.
186    pub value: FieldType,
187    /// Whether the payload carries an explicit presence byte.
188    pub optional: bool,
189}
190/// Codec boundary generated by named-type macros; handwritten implementations are unsupported.
191pub trait Value: Sized {
192    /// Logical name; independent of source path and declaration order.
193    const NAME: &'static str;
194    /// Compiled descriptor, including recursive links.
195    fn definition() -> &'static TypeSchema;
196
197    /// Append a value within the enclosing row's shared budget.
198    /// # Errors
199    /// Refuses field, byte, depth or node bounds.
200    #[doc(hidden)]
201    fn encode_into(&self, writer: &mut Encoder) -> Result<(), Error>;
202
203    /// Decode within the enclosing row's shared budget.
204    /// # Errors
205    /// Refuses malformed values and exceeded bounds.
206    #[doc(hidden)]
207    fn decode_from(reader: &mut Decoder<'_>) -> Result<Self, Error>;
208}
209
210#[derive(Clone, Default)]
211pub(crate) struct TypeGraph {
212    definitions: BTreeMap<&'static str, &'static TypeSchema>,
213    // Addresses only terminate traversal of compiler-emitted static nodes; they
214    // are never identities, persisted bytes or function-pointer comparisons.
215    visited: Vec<&'static TypeSchema>,
216}
217impl TypeGraph {
218    pub fn include(&mut self, value: FieldType) -> Result<(), Error> {
219        let value = if let FieldType::List { item, max_items } = value {
220            if max_items > MAX_COLLECTION_ITEMS as u32 || matches!(item, FieldType::List { .. }) {
221                return Err(Error::InvalidSchema);
222            }
223
224            *item
225        } else {
226            value
227        };
228        let FieldType::Named(link) = value else {
229            return Ok(());
230        };
231        let definition = (link.definition)();
232        if definition.name != link.name {
233            return Err(Error::InvalidSchema);
234        }
235        if self
236            .visited
237            .iter()
238            .any(|seen| std::ptr::eq(*seen, definition))
239        {
240            return Ok(());
241        }
242        if self.visited.len() >= 64 {
243            return Err(Error::InvalidSchema);
244        }
245        self.visited.push(definition);
246        if self
247            .definitions
248            .insert(link.name, definition)
249            .is_some_and(|old| old != definition)
250            || self.definitions.len() > 32
251        {
252            return Err(Error::InvalidSchema);
253        }
254        match &definition.body {
255            TypeBody::Wrapped(FieldType::Named(_)) => return Err(Error::InvalidSchema),
256            TypeBody::Wrapped(value) => self.include(*value)?,
257            TypeBody::Checked(_) => {}
258            TypeBody::Map {
259                key,
260                value,
261                max_items,
262            } => {
263                if *max_items > MAX_COLLECTION_ITEMS as u32 {
264                    return Err(Error::InvalidSchema);
265                }
266                self.include_ordered(*key)?;
267                self.include(value.value)?;
268            }
269            TypeBody::Set { item, max_items } => {
270                if *max_items > MAX_COLLECTION_ITEMS as u32 {
271                    return Err(Error::InvalidSchema);
272                }
273                self.include_ordered(*item)?;
274            }
275            TypeBody::Record(fields) => {
276                if fields.len() > MAX_FIELDS {
277                    return Err(Error::InvalidSchema);
278                }
279                for field in *fields {
280                    self.include(field.value)?;
281                }
282            }
283            TypeBody::Enum(variants) => {
284                if variants.len() > 64 {
285                    return Err(Error::InvalidSchema);
286                }
287                for variant in *variants {
288                    if let Some(payload) = variant.payload {
289                        self.include(payload.value)?;
290                    }
291                }
292            }
293        }
294
295        Ok(())
296    }
297
298    fn include_ordered(&mut self, value: FieldType) -> Result<(), Error> {
299        match crate::key::operand_type(value) {
300            FieldType::List { .. } => return Err(Error::InvalidSchema),
301            FieldType::Named(link) if unit_enum_len((link.definition)()).is_none() => {
302                return Err(Error::InvalidSchema);
303            }
304            _ => {}
305        }
306
307        self.include(value)
308    }
309
310    pub fn definitions(&self) -> impl Iterator<Item = &'static TypeSchema> + '_ {
311        self.definitions.values().copied()
312    }
313
314    pub fn contains(&self, other: &Self) -> bool {
315        other
316            .definitions
317            .iter()
318            .all(|(name, definition)| self.definitions.get(name) == Some(definition))
319    }
320
321    pub fn encode(&mut self, bytes: &mut Vec<u8>) -> Result<(), Error> {
322        if self.definitions.is_empty() {
323            return Ok(());
324        }
325        bytes.extend(b"ICDBTY02");
326        bytes.extend((MAX_DEPTH as u32).to_le_bytes());
327        bytes.extend((MAX_NODES as u32).to_le_bytes());
328        bytes.extend((self.definitions.len() as u32).to_le_bytes());
329        for definition in self.definitions.values() {
330            let (kind, count) = match &definition.body {
331                TypeBody::Enum(v) => (1, v.len()),
332                TypeBody::Record(f) => (2, f.len()),
333                TypeBody::Set { .. } => (3, 1),
334                TypeBody::Map { .. } => (4, 2),
335                TypeBody::Wrapped(_) => (5, 1),
336                TypeBody::Checked(_) => (6, 1),
337            };
338            bytes.push(kind);
339            name(bytes, definition.name)?;
340            bytes.extend((count as u32).to_le_bytes());
341
342            match &definition.body {
343                TypeBody::Wrapped(value) => encode_type(bytes, *value, false, false)?,
344                TypeBody::Checked(rule) => {
345                    encode_type(bytes, rule.primitive(), false, false)?;
346                    match rule {
347                        NewtypeRule::NonAnonymous => bytes.push(1),
348                        NewtypeRule::Text {
349                            non_blank,
350                            max_chars,
351                            ..
352                        } => {
353                            if !non_blank && max_chars.is_none() {
354                                return Err(Error::InvalidSchema);
355                            }
356                            bytes.extend([2, u8::from(*non_blank), u8::from(max_chars.is_some())]);
357                            if let Some(max) = max_chars {
358                                bytes.extend(max.to_le_bytes());
359                            }
360                        }
361                    }
362                }
363                TypeBody::Map {
364                    key,
365                    value,
366                    max_items,
367                } => {
368                    bytes.extend(max_items.to_le_bytes());
369                    bytes.extend((MAX_COLLECTION_ITEMS as u32).to_le_bytes());
370                    encode_type(bytes, *key, false, false)?;
371                    encode_type(bytes, value.value, value.optional, false)?;
372                }
373                TypeBody::Set { item, max_items } => {
374                    bytes.extend(max_items.to_le_bytes());
375                    bytes.extend((MAX_COLLECTION_ITEMS as u32).to_le_bytes());
376                    encode_type(bytes, *item, false, false)?;
377                }
378                TypeBody::Enum(variants) => {
379                    if variants.is_empty()
380                        || variants.len() > 64
381                        || variants.windows(2).any(|w| w[0].name >= w[1].name)
382                    {
383                        return Err(Error::InvalidSchema);
384                    }
385                    for variant in *variants {
386                        name(bytes, variant.name)?;
387                        bytes.push(u8::from(variant.payload.is_some()));
388                        if let Some(payload) = variant.payload {
389                            encode_type(bytes, payload.value, payload.optional, false)?;
390                        }
391                    }
392                }
393                TypeBody::Record(fields) => {
394                    if fields.len() > MAX_FIELDS
395                        || fields.windows(2).any(|w| w[0].name >= w[1].name)
396                    {
397                        return Err(Error::InvalidSchema);
398                    }
399                    for field in *fields {
400                        if field.reference.is_some()
401                            || field.default.is_some()
402                            || field.managed.is_some()
403                        {
404                            return Err(Error::InvalidSchema);
405                        }
406                        name(bytes, field.name)?;
407                        encode_type(bytes, field.value, field.optional, false)?;
408                    }
409                }
410            }
411        }
412        // Least fixed point: an optional/list edge or unit alternative is a finite
413        // constructor; a required cycle without a base case never becomes viable.
414        let mut finite = BTreeSet::new();
415        for _ in 0..self.definitions.len() {
416            for (name, definition) in &self.definitions {
417                let viable = |value, optional| {
418                    optional
419                        || match value {
420                            FieldType::Named(link) => finite.contains(link.name),
421                            _ => true,
422                        }
423                };
424                let has_value = match &definition.body {
425                    TypeBody::Wrapped(_)
426                    | TypeBody::Checked(_)
427                    | TypeBody::Set { .. }
428                    | TypeBody::Map { .. } => true,
429                    TypeBody::Record(fields) => fields.iter().all(|f| viable(f.value, f.optional)),
430                    TypeBody::Enum(variants) => variants
431                        .iter()
432                        .any(|v| v.payload.is_none_or(|p| viable(p.value, p.optional))),
433                };
434                if has_value {
435                    finite.insert(*name);
436                }
437            }
438        }
439        if finite.len() != self.definitions.len() {
440            return Err(Error::InvalidSchema);
441        }
442        self.visited = Vec::new();
443
444        Ok(())
445    }
446}