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