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
178fn valid_variants(variants: &[VariantSchema]) -> bool {
179    (1..=64).contains(&variants.len())
180        && variants.iter().all(|v| (1..=64).contains(&v.name.len()))
181        && variants.windows(2).all(|w| w[0].name < w[1].name)
182}
183
184// Ordered capability belongs to the complete enum, including unused variants.
185// Bound unchecked operand definitions before comparing them with admitted metadata.
186pub(crate) fn unit_enum_len(definition: &TypeSchema) -> Option<usize> {
187    let TypeBody::Enum(variants) = &definition.body else {
188        return None;
189    };
190
191    (!definition.name.is_empty()
192        && definition.name.len() <= 64
193        && valid_variants(variants)
194        && variants.iter().all(|v| v.payload.is_none()))
195    .then_some(variants.len())
196}
197/// Payload shape, shared with the field type/optionality rules.
198#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
199pub struct ValueSchema {
200    /// Exact scalar, bounded list or compiler-resolved named type.
201    pub value: FieldType,
202    /// Whether the payload carries an explicit presence byte.
203    pub optional: bool,
204}
205/// Codec boundary generated by named-type macros; handwritten implementations are unsupported.
206pub trait Value: Sized {
207    /// Logical name; independent of source path and declaration order.
208    const NAME: &'static str;
209    /// Compiled descriptor, including recursive links.
210    fn definition() -> &'static TypeSchema;
211
212    /// Append a value within the enclosing row's shared budget.
213    /// # Errors
214    /// Refuses field, byte, depth or node bounds.
215    #[doc(hidden)]
216    fn encode_into(&self, writer: &mut Encoder) -> Result<(), Error>;
217
218    /// Decode within the enclosing row's shared budget.
219    /// # Errors
220    /// Refuses malformed values and exceeded bounds.
221    #[doc(hidden)]
222    fn decode_from(reader: &mut Decoder<'_>) -> Result<Self, Error>;
223}
224
225#[derive(Default)]
226pub(crate) struct TypeGraph {
227    definitions: BTreeMap<&'static str, &'static TypeSchema>,
228    // Addresses only terminate traversal of compiler-emitted static nodes; they
229    // are never identities, persisted bytes or function-pointer comparisons.
230    visited: BTreeSet<usize>,
231}
232impl TypeGraph {
233    pub fn include(&mut self, value: FieldType) -> Result<(), Error> {
234        let mut pending = Vec::new();
235        let mut first = Some(value);
236        while let Some(value) = first.take().or_else(|| pending.pop()) {
237            let value = if let FieldType::List { item, max_items } = value {
238                if max_items > MAX_COLLECTION_ITEMS as u32 || matches!(item, FieldType::List { .. })
239                {
240                    return Err(Error::InvalidSchema);
241                }
242
243                *item
244            } else {
245                value
246            };
247            let FieldType::Named(link) = value else {
248                continue;
249            };
250            let definition = (link.definition)();
251            if definition.name != link.name {
252                return Err(Error::InvalidSchema);
253            }
254            if !self.visited.insert(std::ptr::from_ref(definition).addr()) {
255                continue;
256            }
257            if self
258                .definitions
259                .insert(link.name, definition)
260                .is_some_and(|old| old != definition)
261            {
262                return Err(Error::InvalidSchema);
263            }
264            match &definition.body {
265                TypeBody::Wrapped(FieldType::Named(_)) => return Err(Error::InvalidSchema),
266                TypeBody::Wrapped(value) => pending.push(*value),
267                TypeBody::Checked(_) => {}
268                TypeBody::Map {
269                    key,
270                    value,
271                    max_items,
272                } => {
273                    if *max_items > MAX_COLLECTION_ITEMS as u32 {
274                        return Err(Error::InvalidSchema);
275                    }
276                    Self::validate_ordered(*key)?;
277                    pending.push(*key);
278                    pending.push(value.value);
279                }
280                TypeBody::Set { item, max_items } => {
281                    if *max_items > MAX_COLLECTION_ITEMS as u32 {
282                        return Err(Error::InvalidSchema);
283                    }
284                    Self::validate_ordered(*item)?;
285                    pending.push(*item);
286                }
287                TypeBody::Record(fields) => {
288                    if fields.len() > MAX_FIELDS {
289                        return Err(Error::InvalidSchema);
290                    }
291                    for field in *fields {
292                        pending.push(field.value);
293                    }
294                }
295                TypeBody::Enum(variants) => {
296                    if variants.len() > 64 {
297                        return Err(Error::InvalidSchema);
298                    }
299                    for variant in *variants {
300                        if let Some(payload) = variant.payload {
301                            pending.push(payload.value);
302                        }
303                    }
304                }
305            }
306        }
307        Ok(())
308    }
309
310    fn validate_ordered(value: FieldType) -> Result<(), Error> {
311        match crate::key::operand_type(value) {
312            FieldType::List { .. } => return Err(Error::InvalidSchema),
313            FieldType::Named(link) if unit_enum_len((link.definition)()).is_none() => {
314                return Err(Error::InvalidSchema);
315            }
316            _ => {}
317        }
318
319        Ok(())
320    }
321
322    pub fn definitions(&self) -> impl Iterator<Item = &'static TypeSchema> + '_ {
323        self.definitions.values().copied()
324    }
325
326    pub fn contains(&self, other: &Self) -> bool {
327        other
328            .definitions
329            .iter()
330            .all(|(name, definition)| self.definitions.get(name) == Some(definition))
331    }
332
333    pub fn encode(&mut self, bytes: &mut Vec<u8>) -> Result<(), Error> {
334        if self.definitions.is_empty() {
335            return Ok(());
336        }
337        bytes.extend(b"ic-db:named-types\0");
338        bytes.extend((MAX_DEPTH as u32).to_le_bytes());
339        bytes.extend((MAX_NODES as u32).to_le_bytes());
340        let count = u32::try_from(self.definitions.len()).map_err(|_| Error::InvalidSchema)?;
341        bytes.extend(count.to_le_bytes());
342        for definition in self.definitions.values() {
343            let (kind, count) = match &definition.body {
344                TypeBody::Enum(v) => (1, v.len()),
345                TypeBody::Record(f) => (2, f.len()),
346                TypeBody::Set { .. } => (3, 1),
347                TypeBody::Map { .. } => (4, 2),
348                TypeBody::Wrapped(_) => (5, 1),
349                TypeBody::Checked(_) => (6, 1),
350            };
351            bytes.push(kind);
352            name(bytes, definition.name)?;
353            bytes.extend((count as u32).to_le_bytes());
354
355            match &definition.body {
356                TypeBody::Wrapped(value) => encode_type(bytes, *value, false, false)?,
357                TypeBody::Checked(rule) => {
358                    encode_type(bytes, rule.primitive(), false, false)?;
359                    match rule {
360                        NewtypeRule::NonAnonymous => bytes.push(1),
361                        NewtypeRule::Text {
362                            non_blank,
363                            max_chars,
364                            max_bytes,
365                        } => {
366                            if (!non_blank && max_chars.is_none())
367                                || (*non_blank && (*max_bytes == 0 || *max_chars == Some(0)))
368                            {
369                                return Err(Error::InvalidSchema);
370                            }
371                            bytes.extend([2, u8::from(*non_blank), u8::from(max_chars.is_some())]);
372                            if let Some(max) = max_chars {
373                                bytes.extend(max.to_le_bytes());
374                            }
375                        }
376                    }
377                }
378                TypeBody::Map {
379                    key,
380                    value,
381                    max_items,
382                } => {
383                    bytes.extend(max_items.to_le_bytes());
384                    bytes.extend((MAX_COLLECTION_ITEMS as u32).to_le_bytes());
385                    encode_type(bytes, *key, false, false)?;
386                    encode_type(bytes, value.value, value.optional, false)?;
387                }
388                TypeBody::Set { item, max_items } => {
389                    bytes.extend(max_items.to_le_bytes());
390                    bytes.extend((MAX_COLLECTION_ITEMS as u32).to_le_bytes());
391                    encode_type(bytes, *item, false, false)?;
392                }
393                TypeBody::Enum(variants) => {
394                    if !valid_variants(variants) {
395                        return Err(Error::InvalidSchema);
396                    }
397                    for variant in *variants {
398                        name(bytes, variant.name)?;
399                        bytes.push(u8::from(variant.payload.is_some()));
400                        if let Some(payload) = variant.payload {
401                            encode_type(bytes, payload.value, payload.optional, false)?;
402                        }
403                    }
404                }
405                TypeBody::Record(fields) => {
406                    if fields.len() > MAX_FIELDS
407                        || fields.windows(2).any(|w| w[0].name >= w[1].name)
408                    {
409                        return Err(Error::InvalidSchema);
410                    }
411                    for field in *fields {
412                        if field.reference.is_some()
413                            || field.default.is_some()
414                            || field.managed.is_some()
415                        {
416                            return Err(Error::InvalidSchema);
417                        }
418                        name(bytes, field.name)?;
419                        encode_type(bytes, field.value, field.optional, false)?;
420                    }
421                }
422            }
423        }
424        self.validate_finite()?;
425        self.visited.clear();
426        Ok(())
427    }
428
429    fn validate_finite(&self) -> Result<(), Error> {
430        let mut dependents = BTreeMap::<_, Vec<_>>::new();
431        let mut remaining = BTreeMap::new();
432        let mut ready = Vec::new();
433        for definition in self.definitions() {
434            // Only required record/enum edges can propagate a recursive obligation.
435            let mut requires = |value: FieldType, optional: bool| {
436                if let FieldType::Named(link) = value
437                    && !optional
438                    && matches!(
439                        (link.definition)().body,
440                        TypeBody::Record(_) | TypeBody::Enum(_)
441                    )
442                {
443                    dependents
444                        .entry(link.name)
445                        .or_default()
446                        .push(definition.name);
447                    true
448                } else {
449                    false
450                }
451            };
452            // A record needs every required field. An enum needs one finite alternative.
453            let needed = match definition.body {
454                TypeBody::Record(fields) => fields
455                    .iter()
456                    .filter(|f| requires(f.value, f.optional))
457                    .count(),
458                TypeBody::Enum(variants) => usize::from(
459                    variants
460                        .iter()
461                        .all(|v| v.payload.is_some_and(|p| requires(p.value, p.optional))),
462                ),
463                TypeBody::Wrapped(_)
464                | TypeBody::Checked(_)
465                | TypeBody::Set { .. }
466                | TypeBody::Map { .. } => continue,
467            };
468            if needed == 0 {
469                ready.push(definition.name);
470            } else {
471                remaining.insert(definition.name, needed);
472            }
473        }
474        while let Some(name) = ready.pop() {
475            for parent in dependents.remove(name).into_iter().flatten() {
476                if let std::collections::btree_map::Entry::Occupied(mut entry) =
477                    remaining.entry(parent)
478                {
479                    *entry.get_mut() -= 1;
480                    if *entry.get() == 0 {
481                        entry.remove();
482                        ready.push(parent);
483                    }
484                }
485            }
486        }
487        if remaining.is_empty() {
488            Ok(())
489        } else {
490            Err(Error::InvalidSchema)
491        }
492    }
493}