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