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, sync::Arc};
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 share the admitted entity roster and named definitions; each 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    metadata: Arc<SchemaMetadata>,
405    pub(crate) fingerprint: [u8; 32],
406}
407
408struct SchemaMetadata {
409    entities: Vec<&'static EntitySchema>,
410    types: TypeGraph,
411}
412
413/// Serializable inspection of one compiled store or a single entity in it.
414#[derive(serde::Serialize)]
415pub struct SchemaDescription<'a> {
416    /// Fingerprint of the entire compiled store, including for an entity selection.
417    pub fingerprint: [u8; 32],
418    /// Selected entities in logical-name order.
419    pub entities: &'a [&'static EntitySchema],
420    /// Reachable named definitions in logical-name order. Links serialize by name.
421    pub types: Vec<&'static crate::TypeSchema>,
422}
423
424impl Schema {
425    /// Validate one bounded compiled schema and compute its canonical fingerprint.
426    /// # Errors
427    /// Refuses duplicate/invalid identities, fields, keys, indexes or capacity.
428    pub fn new(entities: &[&'static EntitySchema]) -> Result<Self, Error> {
429        Self::admit_schema(entities, |_, _, _, _| {})
430    }
431
432    // The host formats reference failures at the same check used by ordinary admission.
433    pub(crate) fn admit_schema(
434        entities: &[&'static EntitySchema],
435        report_reference: impl FnOnce(&str, &FieldSchema, &str, Option<(&str, FieldType)>),
436    ) -> Result<Self, Error> {
437        if entities.is_empty() || entities.len() > usize::from(MAX_ENTITIES) {
438            return Err(Error::InvalidSchema);
439        }
440        let mut entities = entities.to_vec();
441        entities.sort_by_key(|entity| entity.name);
442        let mut bytes = Vec::new();
443        // The hash domain identifies the compiled schema grammar. These versions
444        // identify independent row, key, semantics and supplier contracts.
445        // Supplier contract 1 is qualified with Storage 0.74.1; it is not a guess
446        // that every future supplier release uses a compatible collection format.
447        // Semantics 2 admits complete physical index keys of at most 512 bytes.
448        // Older wider-key contracts refuse intact; stored component bytes are unchanged.
449        for version in [crate::codec::ROW_CODEC_VERSION, 1, 2, 1] {
450            bytes.extend(version.to_le_bytes());
451        }
452        bytes.extend((entities.len() as u32).to_le_bytes());
453        let mut ids = BTreeSet::new();
454        let mut types = TypeGraph::default();
455        for entity in &entities {
456            if entity.id != handle(entity.name)
457                || !ids.insert(entity.id)
458                || entity.fields.is_empty()
459                || !(1..=crate::codec::MAX_ROW_BYTES).contains(&entity.max_row_bytes)
460                || entity.fields.len() > MAX_FIELDS
461                || entity.indexes.len() > 8
462                || !entity.key_type().is_ok_and(RowKey::supports)
463                || entity
464                    .fields
465                    .windows(2)
466                    .any(|pair| pair[0].name >= pair[1].name)
467            {
468                return Err(Error::InvalidSchema);
469            }
470            name(&mut bytes, entity.name)?;
471            if entity.max_row_bytes != crate::codec::DEFAULT_ROW_BYTES {
472                // A zero field count is reserved; a real entity always has a key.
473                bytes.extend(0_u32.to_le_bytes());
474                bytes.extend((entity.max_row_bytes as u32).to_le_bytes());
475            }
476            bytes.extend((entity.fields.len() as u32).to_le_bytes());
477            let mut list_fanout = 0;
478            let mut list_indexes = BTreeSet::new();
479            for field in entity.fields {
480                name(&mut bytes, field.name)?;
481                encode_type(
482                    &mut bytes,
483                    field.value,
484                    field.optional,
485                    field.reference.is_some(),
486                )?;
487                types.include(field.value)?;
488                if let Some(reference) = field.reference {
489                    let Some(target) = entities.iter().find(|target| {
490                        target.id == reference.entity && target.name == reference.entity_name
491                    }) else {
492                        report_reference(entity.name, field, reference.entity_name, None);
493
494                        return Err(Error::InvalidSchema);
495                    };
496                    let key_type = target.key_type().map_err(|_| Error::InvalidSchema)?;
497                    let referenced_type = match field.value {
498                        FieldType::List { item, .. } => *item,
499                        scalar => scalar,
500                    };
501                    if referenced_type != key_type {
502                        report_reference(
503                            entity.name,
504                            field,
505                            target.name,
506                            Some((target.primary_key, key_type)),
507                        );
508
509                        return Err(Error::InvalidSchema);
510                    }
511                    if let FieldType::List { max_items, .. } = field.value {
512                        list_fanout += max_items;
513                        if list_fanout > 32
514                            || reference.index != handle(field.name)
515                            || !list_indexes.insert(reference.index)
516                        {
517                            return Err(Error::InvalidSchema);
518                        }
519                        name(&mut bytes, target.name)?;
520                        name(&mut bytes, field.name)?;
521                        continue;
522                    }
523                    if !RowKey::supports(field.value) {
524                        return Err(Error::InvalidSchema);
525                    }
526                    let index = entity
527                        .indexes
528                        .iter()
529                        .find(|index| {
530                            index.id == reference.index
531                                && !index.present_only
532                                && index.fields.first() == Some(&field.name)
533                        })
534                        .ok_or(Error::InvalidSchema)?;
535                    name(&mut bytes, target.name)?;
536                    name(&mut bytes, index.name)?;
537                }
538            }
539            name(&mut bytes, entity.primary_key)?;
540            bytes.extend((entity.indexes.len() as u32).to_le_bytes());
541            let mut index_ids = BTreeSet::new();
542            for index in entity.indexes {
543                if index.id != handle(index.name)
544                    || !index_ids.insert(index.id)
545                    || index.fields.is_empty()
546                    || index.fields.len() > 4
547                {
548                    return Err(Error::InvalidSchema);
549                }
550                let mut fields = BTreeSet::new();
551                let has_optional = index.fields.iter().any(|name| {
552                    entity
553                        .fields
554                        .iter()
555                        .any(|field| field.name == *name && field.optional)
556                });
557                if (index.unique && has_optional && !index.present_only)
558                    || (index.present_only && (!index.unique || !has_optional))
559                {
560                    return Err(Error::InvalidSchema);
561                }
562                name(&mut bytes, index.name)?;
563                bytes.push(u8::from(index.unique) | (u8::from(index.present_only) << 1));
564                bytes.extend((index.fields.len() as u32).to_le_bytes());
565                for field in index.fields {
566                    if !fields.insert(field) {
567                        return Err(Error::InvalidSchema);
568                    }
569                    if let Some(declared) = entity.field_by_name(field) {
570                        if !key::supports(declared.value) {
571                            return Err(Error::InvalidSchema);
572                        }
573                        name(&mut bytes, field)?;
574                    } else {
575                        let (parent, member) =
576                            entity.record_member(field).ok_or(Error::InvalidSchema)?;
577                        let parent = &entity.fields[parent];
578                        let leaf = member.field();
579                        if index.unique || index.fields.len() != 1 {
580                            return Err(Error::InvalidSchema);
581                        }
582                        // Outside the 1..=64 length domain of a flat field. Each path part
583                        // owns its own frame, including when the index has an explicit name.
584                        bytes.extend(u32::MAX.to_le_bytes());
585                        name(&mut bytes, parent.name)?;
586                        name(&mut bytes, leaf.name)?;
587                    }
588                }
589            }
590            if entity
591                .indexes
592                .windows(2)
593                .any(|pair| pair[0].name >= pair[1].name)
594            {
595                return Err(Error::InvalidSchema);
596            }
597        }
598        types.encode(&mut bytes)?;
599        // Versioned policy trailer only for schemas that declare defaults. Existing
600        // contracts retain their bytes; the trailer is not a second durable catalog.
601        let defaults: Vec<_> = entities
602            .iter()
603            .flat_map(|entity| {
604                entity
605                    .fields
606                    .iter()
607                    .filter_map(move |field| field.default.map(|value| (entity, field, value)))
608            })
609            .collect();
610        if !defaults.is_empty() {
611            bytes.extend(b"ic-db:insert-defaults:v1\0");
612            bytes.extend((defaults.len() as u32).to_le_bytes());
613            for (entity, field, value) in defaults {
614                if field.name == entity.primary_key {
615                    return Err(Error::InvalidSchema);
616                }
617                name(&mut bytes, entity.name)?;
618                name(&mut bytes, field.name)?;
619                let encoded = value.encode(field.value)?;
620                bytes.extend((encoded.len() as u32).to_le_bytes());
621                bytes.extend(encoded);
622            }
623        }
624        let mut policies = Vec::new();
625        for entity in &entities {
626            let mut seen = [false; 2];
627            for field in entity.fields {
628                if let Some(managed) = field.managed {
629                    if crate::key::operand_type(field.value) != FieldType::Timestamp
630                        || field.optional
631                        || field.default.is_some()
632                        || field.reference.is_some()
633                        || field.name == entity.primary_key
634                        || seen[managed.slot()]
635                    {
636                        return Err(Error::InvalidSchema);
637                    }
638                    seen[managed.slot()] = true;
639                    policies.push((entity.name, field.name, managed));
640                }
641            }
642        }
643        if !policies.is_empty() {
644            bytes.extend(b"ic-db:managed-times:v1\0");
645            bytes.extend((policies.len() as u32).to_le_bytes());
646            for (entity, field, managed) in policies {
647                name(&mut bytes, entity)?;
648                name(&mut bytes, field)?;
649                bytes.push(managed.slot() as u8 + 1);
650            }
651        }
652        let mut hash = Sha256::new();
653        hash.update(b"ic-db:compiled-schema:v1\0");
654        hash.update(bytes);
655
656        Ok(Self {
657            metadata: Arc::new(SchemaMetadata { entities, types }),
658            fingerprint: hash.finalize().into(),
659        })
660    }
661
662    /// Full domain-separated contract identity used by the durable manifest.
663    #[must_use]
664    pub const fn fingerprint(&self) -> [u8; 32] {
665        self.fingerprint
666    }
667
668    /// Compiled entities in logical-name order, for bounded inspection.
669    #[must_use]
670    pub fn entities(&self) -> &[&'static EntitySchema] {
671        &self.metadata.entities
672    }
673
674    /// Describe the compiled schema without opening storage. A selected entity
675    /// includes its reachable named values. References identify other entities
676    /// without expanding them. Schema admission bounds the entities and definitions.
677    /// # Errors
678    /// Returns `UnknownEntity` for an unknown name or a schema error if a type
679    /// resolver fails to reproduce its admitted declaration.
680    pub fn describe(&self, selected: Option<&str>) -> Result<SchemaDescription<'_>, Error> {
681        let (entities, types) = if let Some(name) = selected {
682            let position = self
683                .entities()
684                .binary_search_by_key(&name, |entity| entity.name)
685                .map_err(|_| Error::UnknownEntity)?;
686            let entity = self.entities()[position];
687            let mut reachable = TypeGraph::default();
688            for field in entity.fields {
689                reachable.include(field.value)?;
690            }
691            if !self.metadata.types.contains(&reachable) {
692                return Err(Error::InvalidSchema);
693            }
694            (
695                &self.entities()[position..=position],
696                reachable.definitions().collect(),
697            )
698        } else {
699            (self.entities(), self.types().collect())
700        };
701        Ok(SchemaDescription {
702            fingerprint: self.fingerprint(),
703            entities,
704            types,
705        })
706    }
707
708    pub(crate) fn entity_by_id(&self, id: u32) -> Option<&'static EntitySchema> {
709        self.entities()
710            .iter()
711            .copied()
712            .find(|entity| entity.id == id)
713    }
714
715    pub(crate) fn entity_by_name(&self, name: &str) -> Option<&'static EntitySchema> {
716        self.entities()
717            .binary_search_by_key(&name, |entity| entity.name)
718            .ok()
719            .map(|position| self.entities()[position])
720    }
721
722    /// Reachable named definitions in logical-name order, without expanding cycles.
723    pub fn types(&self) -> impl Iterator<Item = &'static crate::TypeSchema> + '_ {
724        self.metadata.types.definitions()
725    }
726
727    // Return the existing admitted descriptor after checking the complete type
728    // contract. Typed callers can use it without specializing execution around
729    // their executable's descriptor address.
730    pub(crate) fn admits(&self, proposed: &EntitySchema) -> Result<&'static EntitySchema, Error> {
731        let current = self.entity_by_id(proposed.id).ok_or(Error::UnknownEntity)?;
732        // The exact immutable descriptor and its compiled links were checked by Schema::new.
733        if std::ptr::eq(current, proposed) {
734            return Ok(current);
735        }
736        if current.max_row_bytes != proposed.max_row_bytes
737            || current.name != proposed.name
738            || current.fields != proposed.fields
739            || current.primary_key != proposed.primary_key
740            || current.indexes != proposed.indexes
741        {
742            return Err(Error::UnknownEntity);
743        }
744        let mut proposed_types = TypeGraph::default();
745        for field in proposed.fields {
746            proposed_types
747                .include(field.value)
748                .map_err(|_| Error::UnknownEntity)?;
749        }
750        if !self.metadata.types.contains(&proposed_types) {
751            return Err(Error::UnknownEntity);
752        }
753
754        Ok(current)
755    }
756}
757
758pub(crate) fn name(bytes: &mut Vec<u8>, value: &str) -> Result<(), Error> {
759    if value.is_empty() || value.len() > 64 {
760        return Err(Error::InvalidSchema);
761    }
762    bytes.extend((value.len() as u32).to_le_bytes());
763    bytes.extend(value.as_bytes());
764
765    Ok(())
766}
767
768pub(crate) fn encode_type(
769    bytes: &mut Vec<u8>,
770    value: FieldType,
771    optional: bool,
772    reference: bool,
773) -> Result<(), Error> {
774    let tag = match value {
775        FieldType::Nat64 => 1,
776        FieldType::Bool => 2,
777        FieldType::Text { .. } => 3,
778        FieldType::Int64 => 4,
779        FieldType::Nat128 => 5,
780        FieldType::Int128 => 6,
781        FieldType::Blob { .. } => 7,
782        FieldType::Nat8 => 8,
783        FieldType::Nat16 => 9,
784        FieldType::Nat32 => 10,
785        FieldType::Int8 => 11,
786        FieldType::Int16 => 12,
787        FieldType::Int32 => 13,
788        FieldType::Principal => 14,
789        FieldType::Named(_) => 15,
790        FieldType::List { .. } => 16,
791        FieldType::U256 => 17,
792        FieldType::Float32 => 18,
793        FieldType::Float64 => 19,
794        FieldType::Subaccount => 20,
795        FieldType::Account => 21,
796        FieldType::Ulid => 22,
797        FieldType::Date => 23,
798        FieldType::Timestamp => 24,
799        FieldType::Duration => 25,
800        FieldType::Decimal { .. } => 26,
801    };
802    bytes.push(tag | if optional { 0x80 } else { 0 } | if reference { 0x40 } else { 0 });
803    match value {
804        FieldType::Decimal { scale } => {
805            if scale > crate::Decimal::MAX_SCALE {
806                return Err(Error::InvalidSchema);
807            }
808            bytes.extend(scale.to_le_bytes());
809        }
810        FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => {
811            if max_bytes > crate::codec::MAX_ROW_BYTES as u32 {
812                return Err(Error::InvalidSchema);
813            }
814            bytes.extend(max_bytes.to_le_bytes());
815        }
816        FieldType::Named(link) => name(bytes, link.name)?,
817        FieldType::List { item, max_items } => {
818            if max_items > crate::named_schema::MAX_COLLECTION_ITEMS as u32
819                || matches!(item, FieldType::List { .. })
820            {
821                return Err(Error::InvalidSchema);
822            }
823            for bound in [
824                max_items,
825                crate::named_schema::MAX_DEPTH as u32,
826                crate::named_schema::MAX_NODES as u32,
827                crate::named_schema::MAX_COLLECTION_ITEMS as u32,
828            ] {
829                bytes.extend(bound.to_le_bytes());
830            }
831            encode_type(bytes, *item, false, false)?;
832        }
833        _ => {}
834    }
835
836    Ok(())
837}