Skip to main content

ic_db/
schema.rs

1//! One compiled contract, canonical fingerprint and inspection projection.
2
3use crate::{
4    __private::RowInfo,
5    Error, IndexValue,
6    codec::Decoder,
7    key,
8    named_schema::{TypeGraph, TypeLink},
9    primary::RowKey,
10};
11use sha2::{Digest, Sha256};
12use std::collections::BTreeSet;
13
14/// Verify producer-owned membership during constant evaluation. Entries are Rust
15/// paths relative to the crate, separated by a character forbidden in identifiers.
16/// Root entries end with `::` so sibling names sharing a prefix stay independent.
17#[doc(hidden)]
18#[must_use]
19pub const fn check_schema_member(path: &str, root: &str, members: Option<&str>) -> bool {
20    const fn listed(path: &[u8], list: &[u8]) -> bool {
21        let mut start = 0;
22        while start < list.len() {
23            let mut end = start;
24            let mut same = true;
25            while end < list.len() && list[end] != b'|' {
26                let i = end - start;
27                same = same && i < path.len() && path[i] == list[end];
28                end += 1;
29            }
30            if same && end - start == path.len() {
31                return true;
32            }
33            start = end + 1;
34        }
35
36        false
37    }
38    let path = path.as_bytes();
39    let mut first_separator = 0;
40    while first_separator < path.len() && path[first_separator] != b':' {
41        first_separator += 1;
42    }
43    let (_, relative) = path.split_at(first_separator);
44
45    let root = root.as_bytes();
46    let mut index = 0;
47    while index < root.len() {
48        if index == relative.len() || relative[index] != root[index] {
49            return true;
50        }
51        index += 1;
52    }
53
54    match members {
55        Some(paths) => listed(relative, paths.as_bytes()),
56        None => false,
57    }
58}
59
60pub(crate) const MAX_ENTITIES: u8 = 128;
61pub(crate) const MAX_FIELDS: usize = 32;
62
63// FNV-1a is only a compact physical handle, never schema authority. Admission
64// rejects collisions; full names and semantics enter the SHA-256 contract.
65#[doc(hidden)]
66#[must_use]
67pub const fn handle(name: &str) -> u32 {
68    let bytes = name.as_bytes();
69    let mut value = 2_166_136_261_u32;
70    let mut position = 0;
71    while position < bytes.len() {
72        value = (value ^ bytes[position] as u32).wrapping_mul(16_777_619);
73        position += 1;
74    }
75
76    value
77}
78
79/// Stored value semantics supported by this increment.
80#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
81pub enum FieldType {
82    /// An ordered bounded list of scalars or named values.
83    List {
84        /// Exact element type; optional elements and inline lists are not admitted yet.
85        item: &'static FieldType,
86        /// Maximum number of elements, from zero through 256.
87        max_items: u32,
88    },
89    /// A compiler-resolved named value. Scalar newtypes and unit enums support
90    /// secondary keys. Primary and reference keys require supported primitives.
91    Named(TypeLink),
92    /// Exact unsigned 8-bit integer.
93    Nat8,
94    /// Exact unsigned 16-bit integer.
95    Nat16,
96    /// Exact unsigned 32-bit integer.
97    Nat32,
98    /// Exact signed 8-bit integer.
99    Int8,
100    /// Exact signed 16-bit integer.
101    Int16,
102    /// Exact signed 32-bit integer.
103    Int32,
104    /// Exact unsigned 64-bit integer.
105    Nat64,
106    /// Exact signed 64-bit integer, without unsigned or floating-point coercion.
107    Int64,
108    /// Exact unsigned 128-bit integer, without narrowing or floating-point coercion.
109    Nat128,
110    /// Exact signed 128-bit integer, without narrowing or floating-point coercion.
111    Int128,
112    /// Exact unsigned 256-bit integer, stored as 32 big-endian bytes.
113    U256,
114    /// Exact 16-byte ULID, ordered by timestamp prefix then remaining bits.
115    Ulid,
116    /// Gregorian epoch days, bounded to years 0000 through 9999.
117    Date,
118    /// Signed Unix milliseconds; full i64 domain.
119    Timestamp,
120    /// Nonnegative milliseconds; full u64 domain.
121    Duration,
122    /// Exact decimal, stored at the declared fractional scale without rounding.
123    Decimal {
124        /// Number of fractional places, 0 through 28.
125        scale: u32,
126    },
127    /// Finite IEEE-754 single precision, canonical positive zero.
128    Float32,
129    /// Finite IEEE-754 double precision, canonical positive zero.
130    Float64,
131    /// Boolean, without numeric coercion.
132    Bool,
133    /// Opaque IC identity, zero to 29 significant bytes; no authority policy.
134    Principal,
135    /// Exact 32-byte opaque subaccount, ordered lexicographically.
136    Subaccount,
137    /// Platform account identity: owner then effective subaccount; absent and zero agree.
138    Account,
139    /// Exact UTF-8 text, bounded in bytes without implicit normalization.
140    Text {
141        /// Maximum UTF-8 byte length (0..=32768); zero admits only empty text.
142        max_bytes: u32,
143    },
144    /// Exact binary bytes without UTF-8 interpretation or normalization.
145    Blob {
146        /// Maximum payload length (0..=32768); zero admits only an empty value.
147        max_bytes: u32,
148    },
149}
150
151/// One named stored field; type, bounds, optionality and write policy define identity.
152#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
153pub struct FieldSchema {
154    /// Database-owned insertion/update time policy, never applied during decode.
155    pub managed: Option<crate::ManagedTimestamp>,
156    /// Compiled insert-omission policy; no default is applied during decode/update.
157    pub default: Option<&'static crate::LiteralDefault>,
158    /// Stable field identity within its entity.
159    pub name: &'static str,
160    /// Declared primitive and its bounds.
161    pub value: FieldType,
162    /// Whether absence is a stored value, distinct from empty/zero/false.
163    pub optional: bool,
164    /// Present targets must exist; deletion is restricted through a declared index.
165    pub reference: Option<ReferenceSchema>,
166}
167
168/// A required or optional typed reference using an ordinary reverse-lookup index.
169/// An absent optional value has no target; zero remains an ordinary target key.
170#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
171pub struct ReferenceSchema {
172    /// Full logical target identity; its required key type must match this field.
173    pub entity_name: &'static str,
174    /// Generated target storage handle.
175    #[doc(hidden)]
176    pub entity: u32,
177    /// Index on this entity whose first component is the referencing field.
178    pub index: u32,
179}
180
181/// A compiled index over supported exact scalar components.
182#[derive(Debug, PartialEq, Eq, serde::Serialize)]
183pub struct IndexSchema {
184    /// Generated storage handle; use the name when selecting an index.
185    #[doc(hidden)]
186    pub id: u32,
187    /// Logical identity within its entity, included in the stored contract.
188    pub name: &'static str,
189    /// Fields in declared index order.
190    pub fields: &'static [&'static str],
191    /// Whether the complete key must be unique in the final batch state.
192    pub unique: bool,
193    /// Unique membership requires every optional component to be present.
194    pub present_only: bool,
195}
196
197impl IndexSchema {
198    /// An admitted equality prefix identifies at most one owner when it fixes the entire unique key.
199    pub(crate) fn is_unique_lookup(&self, fixed_components: usize) -> bool {
200        self.unique && fixed_components == self.fields.len()
201    }
202}
203
204/// Compiled entity metadata emitted by the entity macro.
205#[derive(serde::Serialize)]
206pub struct EntitySchema {
207    /// Maximum encoded row size, including keys and framing.
208    pub max_row_bytes: usize,
209    /// Generated storage handle; schema authors do not assign this number.
210    #[doc(hidden)]
211    pub id: u32,
212    /// Logical entity identity, included in the stored contract.
213    pub name: &'static str,
214    /// Fields in canonical name order.
215    pub fields: &'static [FieldSchema],
216    /// Supplied scalar primary-key field; its type must implement `PrimaryKey`.
217    pub primary_key: &'static str,
218    /// Indexes ordered by logical name.
219    pub indexes: &'static [IndexSchema],
220}
221
222impl EntitySchema {
223    pub(crate) fn field_position(&self, name: &str) -> Option<usize> {
224        self.fields.iter().position(|field| field.name == name)
225    }
226
227    pub(crate) fn field_by_name(&self, name: &str) -> Option<&FieldSchema> {
228        self.field_position(name)
229            .map(|position| &self.fields[position])
230    }
231
232    pub(crate) fn field_is_required(&self, path: &str) -> bool {
233        self.index_field(path).is_some_and(|field| !field.optional)
234    }
235
236    pub(crate) fn record_member(&self, path: &str) -> Option<(usize, crate::member::RecordMember)> {
237        let (parent, child) = path.split_once('.')?;
238        let position = self.field_position(parent)?;
239        let member =
240            crate::member::RecordMember::resolve(self.fields[position].value, child).ok()?;
241        Some((position, member))
242    }
243
244    pub(crate) fn index_field(&self, name: &str) -> Option<crate::ValueSchema> {
245        let (parent, member) = crate::member::resolve_field(self, name).ok()?;
246        let field = &self.fields[parent];
247        let leaf = member.map_or(field, |m| m.field());
248
249        Some(crate::ValueSchema {
250            value: leaf.value,
251            optional: field.optional || leaf.optional,
252        })
253    }
254
255    pub(crate) fn index_by_name(&self, name: &str) -> Option<&IndexSchema> {
256        self.indexes.iter().find(|index| index.name == name)
257    }
258
259    pub(crate) fn has_managed(&self) -> bool {
260        self.fields.iter().any(|field| field.managed.is_some())
261    }
262
263    pub(crate) fn key_type(&self) -> Result<FieldType, Error> {
264        self.field_by_name(self.primary_key)
265            .filter(|field| !field.optional)
266            .map(|f| f.value)
267            .ok_or(Error::Corrupt)
268    }
269    // Called only for an admitted schema. Validate every stored field but retain
270    // only selected key values; no entity or owned text/blob materialization.
271    pub(crate) fn inspect_row(&self, bytes: &[u8]) -> Result<RowInfo, Error> {
272        let mut values = [IndexValue::Absent; MAX_FIELDS];
273        let mut spans = [(0, 0); MAX_FIELDS];
274        self.inspect_fields(bytes, self.key_fields(), &mut values, Some(&mut spans))?;
275
276        self.row_info(&values, bytes, &spans)
277    }
278
279    pub(crate) fn key_fields(&self) -> u32 {
280        self.fields
281            .iter()
282            .enumerate()
283            .fold(0, |mask, (position, field)| {
284                if field.name == self.primary_key
285                    || self.indexes.iter().any(|i| i.fields.contains(&field.name))
286                {
287                    mask | (1 << position)
288                } else {
289                    mask
290                }
291            })
292    }
293    // One bounded borrowed field view serves mutation integrity and predicates.
294    // Unselected fields are still validated, never silently trusted or materialized.
295    // Callers supply fresh absent slots; filling in place avoids copying the view.
296    // Projection captures validated byte ranges, including presence tags. There
297    // is still one row decoder and one shared depth/node/collection budget.
298    pub(crate) fn inspect_fields<'a>(
299        &self,
300        bytes: &'a [u8],
301        selected: u32,
302        keys: &mut [IndexValue<'a>; MAX_FIELDS],
303        mut spans: Option<&mut [(u16, u16); MAX_FIELDS]>,
304    ) -> Result<(), Error> {
305        let mut reader = Decoder::for_entity(bytes, self)?;
306        let mut times = [None; 2];
307        for (position, field) in self.fields.iter().enumerate() {
308            let start = reader.position();
309            let present = !field.optional || reader.boolean()?;
310            if !present {
311                // The fresh slot remains absent; its presence tag is projected.
312            } else if let Some(managed) = field.managed {
313                let value = reader.timestamp()?;
314                times[managed.slot()] = Some(value);
315                keys[position] = IndexValue::from(value);
316            } else if selected & (1 << position) != 0 {
317                *keys.get_mut(position).ok_or(Error::Corrupt)? =
318                    IndexValue::read(&mut reader, field.value)?;
319            } else {
320                reader.skip(field.value)?;
321            }
322            if let Some(spans) = &mut spans {
323                spans[position] = (start as u16, reader.position() as u16);
324            }
325        }
326        reader.finish()?;
327        crate::managed::validate_order(times)?;
328
329        Ok(())
330    }
331
332    pub(crate) fn row_info<'a>(
333        &self,
334        keys: &[IndexValue<'a>; MAX_FIELDS],
335        bytes: &'a [u8],
336        spans: &[(u16, u16); MAX_FIELDS],
337    ) -> Result<RowInfo, Error> {
338        let position = |name: &str| self.field_position(name).ok_or(Error::Corrupt);
339        let indexes = self
340            .indexes
341            .iter()
342            .map(|index| {
343                let mut components = [(IndexValue::Absent, false); 4];
344                for (slot, name) in components.iter_mut().zip(index.fields) {
345                    *slot = if let Some(position) = self.field_position(name) {
346                        (keys[position], self.fields[position].optional)
347                    } else {
348                        let (parent, member) = self.record_member(name).ok_or(Error::Corrupt)?;
349                        let (start, end) = spans[parent];
350                        let optional = self.fields[parent].optional;
351                        (
352                            member.read(&bytes[usize::from(start)..usize::from(end)], optional)?,
353                            optional || member.field().optional,
354                        )
355                    };
356                    if slot.0 == IndexValue::Absent && !slot.1 {
357                        return Err(Error::Corrupt);
358                    }
359                }
360
361                Ok(key::encode_index(
362                    &components[..index.fields.len()],
363                    index.present_only,
364                ))
365            })
366            .collect::<Result<_, Error>>()?;
367        let key = RowKey::from_index(keys[position(self.primary_key)?])?;
368
369        let mut list_links = Vec::new();
370        for (field, &(start, end)) in self.fields.iter().zip(spans) {
371            if let (Some(reference), FieldType::List { item, max_items }) =
372                (field.reference, field.value)
373            {
374                let mut reader = Decoder::new(&bytes[usize::from(start)..usize::from(end)])?;
375                if !field.optional || reader.boolean()? {
376                    let count = reader.nat32()?;
377                    if count > max_items {
378                        return Err(Error::Corrupt);
379                    }
380                    for _ in 0..count {
381                        list_links.push((
382                            reference.index,
383                            RowKey::from_index(IndexValue::read(&mut reader, *item)?)?,
384                        ));
385                    }
386                }
387                reader.finish()?;
388            }
389        }
390        Ok(RowInfo {
391            key,
392            indexes,
393            list_links,
394        })
395    }
396}
397
398/// Validated executable schema. It is never reconstructed from stored data.
399/// Clones retain only immutable executable metadata; each database open still
400/// validates the current durable manifest independently. Revision reads and
401/// writes validate the affected counters when used, without caching them.
402#[derive(Clone)]
403pub struct Schema {
404    entities: Vec<&'static EntitySchema>,
405    pub(crate) fingerprint: [u8; 32],
406    types: TypeGraph,
407}
408
409/// Serializable inspection of one compiled store or a single entity in it.
410#[derive(serde::Serialize)]
411pub struct SchemaDescription<'a> {
412    /// Fingerprint of the entire compiled store, including for an entity selection.
413    pub fingerprint: [u8; 32],
414    /// Selected entities in logical-name order.
415    pub entities: &'a [&'static EntitySchema],
416    /// Reachable named definitions in logical-name order. Links serialize by name.
417    pub types: Vec<&'static crate::TypeSchema>,
418}
419
420impl Schema {
421    /// Validate one bounded compiled schema and compute its canonical fingerprint.
422    /// # Errors
423    /// Refuses duplicate/invalid identities, fields, keys, indexes or capacity.
424    pub fn new(entities: &[&'static EntitySchema]) -> Result<Self, Error> {
425        Self::admit_schema(entities, |_, _, _, _| {})
426    }
427
428    // The host formats reference failures at the same check used by ordinary admission.
429    pub(crate) fn admit_schema(
430        entities: &[&'static EntitySchema],
431        report_reference: impl FnOnce(&str, &FieldSchema, &str, Option<(&str, FieldType)>),
432    ) -> Result<Self, Error> {
433        if entities.is_empty() || entities.len() > usize::from(MAX_ENTITIES) {
434            return Err(Error::InvalidSchema);
435        }
436        let mut entities = entities.to_vec();
437        entities.sort_by_key(|entity| entity.name);
438        let mut bytes = b"ICDBSC01".to_vec();
439        // Contract grammar, row codec, key codec, semantics, supplier contract.
440        // Supplier contract 1 is qualified with Storage 0.74.1; it is not a guess
441        // that every future supplier release uses a compatible collection format.
442        // Semantics 2 admits complete physical index keys of at most 512 bytes.
443        // Older wider-key contracts refuse intact; stored component bytes are unchanged.
444        for version in [2, crate::codec::ROW_CODEC_VERSION, 1, 2, 1] {
445            bytes.extend(version.to_le_bytes());
446        }
447        bytes.extend((entities.len() as u32).to_le_bytes());
448        let mut ids = BTreeSet::new();
449        let mut types = TypeGraph::default();
450        for entity in &entities {
451            if entity.id != handle(entity.name)
452                || !ids.insert(entity.id)
453                || entity.fields.is_empty()
454                || !(1..=crate::codec::MAX_ROW_BYTES).contains(&entity.max_row_bytes)
455                || entity.fields.len() > MAX_FIELDS
456                || entity.indexes.len() > 8
457                || !entity.key_type().is_ok_and(RowKey::supports)
458                || entity
459                    .fields
460                    .windows(2)
461                    .any(|pair| pair[0].name >= pair[1].name)
462            {
463                return Err(Error::InvalidSchema);
464            }
465            name(&mut bytes, entity.name)?;
466            if entity.max_row_bytes != crate::codec::DEFAULT_ROW_BYTES {
467                // A zero field count is reserved; a real entity always has a key.
468                bytes.extend(0_u32.to_le_bytes());
469                bytes.extend((entity.max_row_bytes as u32).to_le_bytes());
470            }
471            bytes.extend((entity.fields.len() as u32).to_le_bytes());
472            let mut list_fanout = 0;
473            let mut list_indexes = BTreeSet::new();
474            for field in entity.fields {
475                name(&mut bytes, field.name)?;
476                encode_type(
477                    &mut bytes,
478                    field.value,
479                    field.optional,
480                    field.reference.is_some(),
481                )?;
482                types.include(field.value)?;
483                if let Some(reference) = field.reference {
484                    let Some(target) = entities.iter().find(|target| {
485                        target.id == reference.entity && target.name == reference.entity_name
486                    }) else {
487                        report_reference(entity.name, field, reference.entity_name, None);
488
489                        return Err(Error::InvalidSchema);
490                    };
491                    let key_type = target.key_type().map_err(|_| Error::InvalidSchema)?;
492                    let referenced_type = match field.value {
493                        FieldType::List { item, .. } => *item,
494                        scalar => scalar,
495                    };
496                    if referenced_type != key_type {
497                        report_reference(
498                            entity.name,
499                            field,
500                            target.name,
501                            Some((target.primary_key, key_type)),
502                        );
503
504                        return Err(Error::InvalidSchema);
505                    }
506                    if let FieldType::List { max_items, .. } = field.value {
507                        list_fanout += max_items;
508                        if list_fanout > 32
509                            || reference.index != handle(field.name)
510                            || !list_indexes.insert(reference.index)
511                        {
512                            return Err(Error::InvalidSchema);
513                        }
514                        name(&mut bytes, target.name)?;
515                        name(&mut bytes, field.name)?;
516                        continue;
517                    }
518                    if !RowKey::supports(field.value) {
519                        return Err(Error::InvalidSchema);
520                    }
521                    let index = entity
522                        .indexes
523                        .iter()
524                        .find(|index| {
525                            index.id == reference.index
526                                && !index.present_only
527                                && index.fields.first() == Some(&field.name)
528                        })
529                        .ok_or(Error::InvalidSchema)?;
530                    name(&mut bytes, target.name)?;
531                    name(&mut bytes, index.name)?;
532                }
533            }
534            name(&mut bytes, entity.primary_key)?;
535            bytes.extend((entity.indexes.len() as u32).to_le_bytes());
536            let mut index_ids = BTreeSet::new();
537            for index in entity.indexes {
538                if index.id != handle(index.name)
539                    || !index_ids.insert(index.id)
540                    || index.fields.is_empty()
541                    || index.fields.len() > 4
542                {
543                    return Err(Error::InvalidSchema);
544                }
545                let mut fields = BTreeSet::new();
546                let has_optional = index.fields.iter().any(|name| {
547                    entity
548                        .fields
549                        .iter()
550                        .any(|field| field.name == *name && field.optional)
551                });
552                if (index.unique && has_optional && !index.present_only)
553                    || (index.present_only && (!index.unique || !has_optional))
554                {
555                    return Err(Error::InvalidSchema);
556                }
557                name(&mut bytes, index.name)?;
558                bytes.push(u8::from(index.unique) | (u8::from(index.present_only) << 1));
559                bytes.extend((index.fields.len() as u32).to_le_bytes());
560                for field in index.fields {
561                    if !fields.insert(field) {
562                        return Err(Error::InvalidSchema);
563                    }
564                    if let Some(declared) = entity.field_by_name(field) {
565                        if !key::supports(declared.value) {
566                            return Err(Error::InvalidSchema);
567                        }
568                        name(&mut bytes, field)?;
569                    } else {
570                        let (parent, member) =
571                            entity.record_member(field).ok_or(Error::InvalidSchema)?;
572                        let parent = &entity.fields[parent];
573                        let leaf = member.field();
574                        if index.unique || index.fields.len() != 1 {
575                            return Err(Error::InvalidSchema);
576                        }
577                        // Outside the 1..=64 length domain of a flat field. Each path part
578                        // owns its own frame, including when the index has an explicit name.
579                        bytes.extend(u32::MAX.to_le_bytes());
580                        name(&mut bytes, parent.name)?;
581                        name(&mut bytes, leaf.name)?;
582                    }
583                }
584            }
585            if entity
586                .indexes
587                .windows(2)
588                .any(|pair| pair[0].name >= pair[1].name)
589            {
590                return Err(Error::InvalidSchema);
591            }
592        }
593        types.encode(&mut bytes)?;
594        // Versioned policy trailer only for schemas that declare defaults. Existing
595        // contracts retain their bytes; the trailer is not a second durable catalog.
596        let defaults: Vec<_> = entities
597            .iter()
598            .flat_map(|entity| {
599                entity
600                    .fields
601                    .iter()
602                    .filter_map(move |field| field.default.map(|value| (entity, field, value)))
603            })
604            .collect();
605        if !defaults.is_empty() {
606            bytes.extend(b"ic-db:insert-defaults:v1\0");
607            bytes.extend((defaults.len() as u32).to_le_bytes());
608            for (entity, field, value) in defaults {
609                if field.name == entity.primary_key {
610                    return Err(Error::InvalidSchema);
611                }
612                name(&mut bytes, entity.name)?;
613                name(&mut bytes, field.name)?;
614                let encoded = value.encode(field.value)?;
615                bytes.extend((encoded.len() as u32).to_le_bytes());
616                bytes.extend(encoded);
617            }
618        }
619        let mut policies = Vec::new();
620        for entity in &entities {
621            let mut seen = [false; 2];
622            for field in entity.fields {
623                if let Some(managed) = field.managed {
624                    if crate::key::operand_type(field.value) != FieldType::Timestamp
625                        || field.optional
626                        || field.default.is_some()
627                        || field.reference.is_some()
628                        || field.name == entity.primary_key
629                        || seen[managed.slot()]
630                    {
631                        return Err(Error::InvalidSchema);
632                    }
633                    seen[managed.slot()] = true;
634                    policies.push((entity.name, field.name, managed));
635                }
636            }
637        }
638        if !policies.is_empty() {
639            bytes.extend(b"ic-db:managed-times:v1\0");
640            bytes.extend((policies.len() as u32).to_le_bytes());
641            for (entity, field, managed) in policies {
642                name(&mut bytes, entity)?;
643                name(&mut bytes, field)?;
644                bytes.push(managed.slot() as u8 + 1);
645            }
646        }
647        let mut hash = Sha256::new();
648        hash.update(b"ic-db:schema:v1\0");
649        hash.update(bytes);
650
651        Ok(Self {
652            entities,
653            types,
654            fingerprint: hash.finalize().into(),
655        })
656    }
657
658    /// Full domain-separated contract identity used by the durable manifest.
659    #[must_use]
660    pub const fn fingerprint(&self) -> [u8; 32] {
661        self.fingerprint
662    }
663
664    /// Compiled entities in logical-name order, for bounded inspection.
665    #[must_use]
666    pub fn entities(&self) -> &[&'static EntitySchema] {
667        &self.entities
668    }
669
670    /// Describe the compiled schema without opening storage. A selected entity
671    /// includes its reachable named values. References identify other entities
672    /// without expanding them. Schema admission bounds the entities and definitions.
673    /// # Errors
674    /// Returns `UnknownEntity` for an unknown name or a schema error if a type
675    /// resolver fails to reproduce its admitted declaration.
676    pub fn describe(&self, selected: Option<&str>) -> Result<SchemaDescription<'_>, Error> {
677        let (entities, types) = if let Some(name) = selected {
678            let position = self
679                .entities
680                .binary_search_by_key(&name, |entity| entity.name)
681                .map_err(|_| Error::UnknownEntity)?;
682            let entity = self.entities[position];
683            let mut reachable = TypeGraph::default();
684            for field in entity.fields {
685                reachable.include(field.value)?;
686            }
687            if !self.types.contains(&reachable) {
688                return Err(Error::InvalidSchema);
689            }
690            (
691                &self.entities[position..=position],
692                reachable.definitions().collect(),
693            )
694        } else {
695            (self.entities(), self.types().collect())
696        };
697        Ok(SchemaDescription {
698            fingerprint: self.fingerprint(),
699            entities,
700            types,
701        })
702    }
703
704    pub(crate) fn entity_by_id(&self, id: u32) -> Option<&'static EntitySchema> {
705        self.entities.iter().copied().find(|entity| entity.id == id)
706    }
707
708    pub(crate) fn entity_by_name(&self, name: &str) -> Option<&'static EntitySchema> {
709        self.entities
710            .binary_search_by_key(&name, |entity| entity.name)
711            .ok()
712            .map(|position| self.entities[position])
713    }
714
715    /// Reachable named definitions in logical-name order, without expanding cycles.
716    pub fn types(&self) -> impl Iterator<Item = &'static crate::TypeSchema> + '_ {
717        self.types.definitions()
718    }
719
720    // Return the existing admitted descriptor after checking the complete type
721    // contract. Typed callers can use it without specializing execution around
722    // their executable's descriptor address.
723    pub(crate) fn admits(&self, proposed: &EntitySchema) -> Result<&'static EntitySchema, Error> {
724        let current = self.entity_by_id(proposed.id).ok_or(Error::UnknownEntity)?;
725        if current.max_row_bytes != proposed.max_row_bytes
726            || current.name != proposed.name
727            || current.fields != proposed.fields
728            || current.primary_key != proposed.primary_key
729            || current.indexes != proposed.indexes
730        {
731            return Err(Error::UnknownEntity);
732        }
733        let mut proposed_types = TypeGraph::default();
734        for field in proposed.fields {
735            proposed_types
736                .include(field.value)
737                .map_err(|_| Error::UnknownEntity)?;
738        }
739        if !self.types.contains(&proposed_types) {
740            return Err(Error::UnknownEntity);
741        }
742
743        Ok(current)
744    }
745}
746
747pub(crate) fn name(bytes: &mut Vec<u8>, value: &str) -> Result<(), Error> {
748    if value.is_empty() || value.len() > 64 {
749        return Err(Error::InvalidSchema);
750    }
751    bytes.extend((value.len() as u32).to_le_bytes());
752    bytes.extend(value.as_bytes());
753
754    Ok(())
755}
756
757pub(crate) fn encode_type(
758    bytes: &mut Vec<u8>,
759    value: FieldType,
760    optional: bool,
761    reference: bool,
762) -> Result<(), Error> {
763    let tag = match value {
764        FieldType::Nat64 => 1,
765        FieldType::Bool => 2,
766        FieldType::Text { .. } => 3,
767        FieldType::Int64 => 4,
768        FieldType::Nat128 => 5,
769        FieldType::Int128 => 6,
770        FieldType::Blob { .. } => 7,
771        FieldType::Nat8 => 8,
772        FieldType::Nat16 => 9,
773        FieldType::Nat32 => 10,
774        FieldType::Int8 => 11,
775        FieldType::Int16 => 12,
776        FieldType::Int32 => 13,
777        FieldType::Principal => 14,
778        FieldType::Named(_) => 15,
779        FieldType::List { .. } => 16,
780        FieldType::U256 => 17,
781        FieldType::Float32 => 18,
782        FieldType::Float64 => 19,
783        FieldType::Subaccount => 20,
784        FieldType::Account => 21,
785        FieldType::Ulid => 22,
786        FieldType::Date => 23,
787        FieldType::Timestamp => 24,
788        FieldType::Duration => 25,
789        FieldType::Decimal { .. } => 26,
790    };
791    bytes.push(tag | if optional { 0x80 } else { 0 } | if reference { 0x40 } else { 0 });
792    match value {
793        FieldType::Decimal { scale } => {
794            if scale > crate::Decimal::MAX_SCALE {
795                return Err(Error::InvalidSchema);
796            }
797            bytes.extend(scale.to_le_bytes());
798        }
799        FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => {
800            if max_bytes > crate::codec::MAX_ROW_BYTES as u32 {
801                return Err(Error::InvalidSchema);
802            }
803            bytes.extend(max_bytes.to_le_bytes());
804        }
805        FieldType::Named(link) => name(bytes, link.name)?,
806        FieldType::List { item, max_items } => {
807            if max_items > crate::named_schema::MAX_COLLECTION_ITEMS as u32
808                || matches!(item, FieldType::List { .. })
809            {
810                return Err(Error::InvalidSchema);
811            }
812            for bound in [
813                max_items,
814                crate::named_schema::MAX_DEPTH as u32,
815                crate::named_schema::MAX_NODES as u32,
816                crate::named_schema::MAX_COLLECTION_ITEMS as u32,
817            ] {
818                bytes.extend(bound.to_le_bytes());
819            }
820            encode_type(bytes, *item, false, false)?;
821        }
822        _ => {}
823    }
824
825    Ok(())
826}